STL 映射迭代器可以通过递增越界吗?
对于关联容器,++ 运算符可以将迭代器发送到集合末尾吗?
示例:
map<UINT32, UINT32> new_map;
new_map[0] = 0;
new_map[1] = 1;
map<UINT32, UINT32> new_iter = new_map.begin();
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
最后,new_iter == new_map.end(),还是最终陷入未知?
注意:我知道这很混乱,而不是做事的方式。我正在处理一些 WTF 公司代码。
For associative containers, can the ++ operator send an iterator past the end of a collection?
Example:
map<UINT32, UINT32> new_map;
new_map[0] = 0;
new_map[1] = 1;
map<UINT32, UINT32> new_iter = new_map.begin();
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
At the end of this, does new_iter == new_map.end(), or does it end up in the great unknown?
Note: I know this is messed up and not the way to do things. I'm working around some WTF corporate code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果递增结束迭代器,结果是未定义的行为。所以,它可能会保持结束,或者结束,或者通过电子邮件给你的祖母发送山羊的链接。
另请参阅:如果当迭代器指向向量的最后一个元素时将其增加 2 会怎样?
If you increment the end iterator, the result is undefined behavior. So, it could remain end, or go off the end, or email your grandmother a link to goatse.
See also: What if I increment an iterator by 2 when it points onto the last element of a vector?
前向迭代器的 ++ 运算符的先决条件是迭代器是可解引用的。这意味着它不能超过地图的末尾,因此您的代码会给出未定义的行为。 C++ 标准第 24.1.3 节对此进行了描述。
The precondition on the ++ operator for a forward iterator is that the iterator is dereferenceable. This implies it cannot be past the end of the map, so your code gives undefined behaviour. This is described in section 24.1.3 of the C++ Standard.
正如其他人指出的那样,增加结束迭代器会导致未定义的行为,但值得注意的是,Visual Studio 2008 将在运行时抛出调试断言(由于其 检查迭代器)如果你这样做。
As others have pointed out, incrementing the end iterator causes undefined behaviour, however it's worth noting that Visual Studio 2008 will throw a debug assertion at runtime (due to its checked iterators) if you do this.