Is std::vector::begin() - 1 undefined?

一曲冷凌霜 提交于 2020-01-16 09:09:28

问题


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.

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.


回答1:


Yes, it is undefined.

If you want to iterate over elements in reverse, just use rbegin and rend. 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.




回答2:


It is undefined behaviour. But why not use reverse iterators rbegin() and 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



来源:https://stackoverflow.com/questions/18225651/is-stdvectorbegin-1-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!