deque crbegin in C++ STL

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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;
     ^



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.