我需要以向后的顺序迭代一些元素,我使用的是:
for ( /* ... */ it = vec.end() - 1, end = vec.begin() ; it >= end ; --it ) {
// ...
我现在知道end() - 1
是为一些容器定义的,包括向量,但现在我需要知道是否也定义了开始递减。
编辑
我不知道我是否可以使用reverse_iterator,因为我需要将这些迭代器作为参数传递给std::vector::erase,从文档中看,它们是不同的类型。
是的,它是未定义的。
如果要反向迭代元素,只需使用rbegin
和rend
即可。它们是反向迭代器,专门为此目的而设计。如果需要从反向迭代器中获得标准迭代器,可以在迭代器上使用base
成员函数。
这是未定义的行为。但是为什么不使用反向迭代器rbgin()和rend()呢?
std::vector<int> vec{0,1,2,3,4}
for (auto it = vec.rbegin(); it != vec.rend(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
输出
4 3 2 1 0