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:
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque< int > numdeque = { 1, 2, 3, 4, 5, 6 };
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.
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque< int > numdeque = { 1, 2, 3, 4, 5, 6 };
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
Share your thoughts in the comments
Please Login to comment...