是否允许增加结束迭代器? [英] Is it allowed to increment an end iterator?

查看:86
本文介绍了是否允许增加结束迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否允许增加迭代器变量 it 已经在 end(),即 auto it = v.end()

Is it allowed to increment an iterator variable it that already is at end(), i.e. auto it = v.end()?


  • 一般是否允许?

  • 如果没有,是否不允许 vector

  • 如果是,则 ++ it if idempotent if it == v.end()

  • Is it allowed in general?
  • If not, is it not allowed for vector?
  • If yes, is ++it maybe idempotent if it==v.end()?

我问,因为我偶然发现了这样的代码:

I ask, because I stumbled upon code like this:

std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7 };
// delete every other element
for(auto it=v.begin(); it<v.end(); ++it) { // it<end ok? ++it ok on end?
  it = v.erase(it);
}

它适用于g ++ - 6,但这不是证据。

It works fine with g++-6, but that is no proof.

对于一个,它< v.end()可能仅适用于向量,我想它一般应该读取 it!= v.end()。但是在这个不能识别 v 的结尾的例子中如果 ++它已经应用了结束。

For one it<v.end() may only work with vectors, I suppose it should read it!=v.end() in general. But in this example that would not recognize the end of v if ++it is applied when it already is on the end.

推荐答案

行为未定义。您可以将迭代器设置为 end(),但不能将其递增或取消引用它。

No the behaviour is undefined. You are allowed to set an iterator to end(), but you must not increment it or dereference it.

只要背衬容器不是空的,就可以减少它。

You are allowed to decrement it so long as the backing container is not empty.

这篇关于是否允许增加结束迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆