简体   繁体   English

是std :: vector :: begin()-1未定义吗?

[英]Is std::vector::begin() - 1 undefined?

I need to iterate over some elements in backward order and I'm using: 我需要以向后的顺序遍历某些元素,并且正在使用:

for ( /* ... */ it = vec.end() - 1, end = vec.begin() ; it >= end ; --it ) {
    // ...

I now that end() - 1 is defined for some containers, including vector, but now I need to know if begin decrement is also defined. 现在,我为某些容器(包括矢量end() - 1定义了end() - 1 ,但现在我需要知道是否也定义了开始减量。

EDIT 编辑

I don't know if I could use reverse_iterator, because I'll need to pass these iterators as parameters to std::vector::erase and from the documentation, it looks that they are different types. 我不知道是否可以使用reverse_iterator,因为我需要将这些迭代器作为参数传递给std :: vector :: erase,从文档中看,它们是不同的类型。

Yes, it is undefined. 是的,它是未定义的。

If you want to iterate over elements in reverse, just use rbegin and rend . 如果要反向遍历元素,只需使用rbeginrend They're reverse iterators, designed explicitly for this purpose. 它们是反向迭代器,专门为此目的而设计。 If you need to get a standard iterator from the reverse iterator, you can use the base member function on the iterator. 如果需要从反向迭代器中获取标准迭代器,则可以在迭代器上使用base成员函数

It is undefined behaviour. 这是不确定的行为。 But why not use reverse iterators rbegin() and rend() ? 但是,为什么不使用反向迭代器rbegin()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;

output 输出

4 3 2 1 0 4 3 2 1 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM