deque :: crbegin表示constant_reverse_beginner,顾名思义,它返回一个指向deque的最后一个元素的constant_reverse_iterator。
什么是常量迭代器?
常量迭代器不用于修改。它仅用于访问元素。您可以使用non_const迭代器来修改元素。
句法:
dequename.crbegin()
返回值:将const_reverse_iterator返回到序列的相反开头。
应用:
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
下面的程序说明了crbegin函数的工作方式:
// deque::crbegin and crend
#include
#include
using namespace std;
int main()
{
// Declare a deque with the name numdeque
deque 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;
}
Printing the numdeque backwards: 6 5 4 3 2 1
由于返回的迭代器是常量,因此如果尝试更改值,则会出现编译器错误。
// deque::crbegin and crend
#include
#include
using namespace std;
int main()
{
// Declare a deque with the name numdeque
deque 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;
}
输出:
prog.cpp: In function ‘int main()’:
prog.cpp:14:8: error: assignment of read-only location ‘rit.std::reverse_iterator<_iterator>::operator*<:_deque_iterator const int> >()’
*rit = 10;
^