对一个vector反向迭代器的使用例子:
vector<int>::reverse_iterator r_iter;
for (r_iter = vec.rbegin(); // binds r_iter to last element
r_iter != vec.rend(); // rend refers 1 before 1st element
++r_iter) // decrements iterator one element
cout << *r_iter << endl; // prints 9,8,7,...0
用在sort函数上,可以实现从大到小排序:
// sorts vec in "normal" order
sort(vec.begin(), vec.end());
// sorts in reverse: puts smallest element at the end of vec
sort(vec.rbegin(), vec.rend());
用在查找中,可以实现从后往前查找:
一个字符串有很多个句子组成,句子用逗号隔开,现在查找最后一个句子
// find last element in a comma-separated list
string::reverse_iterator rcomma = find(line.rbegin(), line.rend(), ',');
现在将反向迭代器转换成正向迭代器来实现正序输出:
// ok: get a forward iterator and read to end of line
cout << string(rcomma.base(), line.end()) << endl;
使用的是reverse_iterator的base方法