Open In App

deque crbegin in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

deque::crbegin means constant_reverse_beginner and as the name suggests it returns a constant_reverse_iterator pointing to the last element of the deque.

What is a constant iterator?
A constant iterator is not used for modification. It is only used for accessing the elements. You can use non_const iterators for modifying the elements.

Syntax:

dequename.crbegin()

Return Value: It returns a const_reverse_iterator to the reverse beginning of the sequence.

Application:

Given a deque with numbers in the increasing order, print them in non increasing order.
Input: deque{1, 2, 3, 4, 5, 6};
for (auto reverseit = deque.crbegin(); reverseit != deque.crend(); ++reverseit)
cout << ' ' << *reverseit;

Output : 6 5 4 3 2 1

Below program illustrates the working of crbegin function:




// deque::crbegin and crend
#include <deque>
#include <iostream>
using namespace std;
int main()
{
    // Declare a deque with the name numdeque
    deque<int> numdeque = { 1, 2, 3, 4, 5, 6 };
  
    // Print the deque backwards using crbegin and crend
    cout << "Printing the numdeque backwards:";
  
    for (auto rit = numdeque.crbegin(); rit != numdeque.crend(); ++rit)
        cout << ' ' << *rit;
  
    return 0;
}


Output:

Printing the numdeque backwards: 6 5 4 3 2 1

Since the returned iterator is constant, if we try to change value, we get compiler error.




// deque::crbegin and crend
#include <deque>
#include <iostream>
using namespace std;
int main()
{
    // Declare a deque with the name numdeque
    deque<int> numdeque = { 1, 2, 3, 4, 5, 6 };
  
    // Print the deque backwards using crbegin and crend
    cout << "Printing the numdeque backwards:";
  
    for (auto rit = numdeque.crbegin(); rit != numdeque.crend(); ++rit)
         *rit = 10;
  
    return 0;
}


Output:

prog.cpp: In function ‘int main()’:
prog.cpp:14:8: error: assignment of read-only location ‘rit.std::reverse_iterator<_Iterator>::operator* >()’
*rit = 10;
     ^



Last Updated : 27 Dec, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads