STL 映射迭代器可以通过递增越界吗?

发布于 2024-08-02 23:33:00 字数 373 浏览 1 评论 0原文

对于关联容器,++ 运算符可以将迭代器发送到集合末尾吗?

示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浸婚纱 2024-08-09 23:33:00

如果递增结束迭代器,结果是未定义的行为。所以,它可能会保持结束,或者结束,或者通过电子邮件给你的祖母发送山羊的链接。

另请参阅:如果当迭代器指向向量的最后一个元素时将其增加 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?

云淡风轻 2024-08-09 23:33:00

前向迭代器的 ++ 运算符的先决条件是迭代器是可解引用的。这意味着它不能超过地图的末尾,因此您的代码会给出未定义的行为。 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.

彩虹直至黑白 2024-08-09 23:33:00

正如其他人指出的那样,增加结束迭代器会导致未定义的行为,但值得注意的是,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文