比较两个 end() 迭代器
list<int> foo;
list<int> foo2;
list<int>::iterator foo_end = foo.end();
list<int>::iterator foo2_end = foo2.end();
for (list<int>::iterator it = foo.begin(); it != foo2_end; ++foo) <- notice != comparison here
{
...
这允许吗?它能正常工作吗?
我倾向于认为这是依赖于实现的,有人知道标准是否对此有任何说明吗?
list<int> foo;
list<int> foo2;
list<int>::iterator foo_end = foo.end();
list<int>::iterator foo2_end = foo2.end();
for (list<int>::iterator it = foo.begin(); it != foo2_end; ++foo) <- notice != comparison here
{
...
it this allowed? will it work correctly.
I am inclined to think that this is implementation dependent, anyone knows if standard says anything about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个关于此的缺陷报告(LWG 缺陷 446 )。缺陷报告询问比较引用不同容器元素的迭代器是否有效。
缺陷报告中的注释解释了这样做的意图肯定是未定义的,但没有明确说明它是未定义的。
拟议的决议是将以下内容添加到标准中,并明确指出它是未定义的:
编辑:该语言不包含在 C++0x FCD 中。事实上,这个问题已通过 N3066< 中的更改得到解决/a>;特别是以下补充(§24.2.5/2):
There was a defect reported about this (LWG defect 446). The defect report asked whether it is valid to compare iterators that refer to elements of different containers.
Notes in the defect report explain that it was certainly the intention that doing so is undefined, but it is not explicitly stated that it is undefined.
The proposed resolution was to add the following to the standard, explicitly stating that it is undefined:
Edit: That language is not included in the C++0x FCD. This issue was in fact resolved by changes in N3066; specifically the following addition (§24.2.5/2):
是这是允许的(即会编译)。
不它将无法正常工作。
foo2_end
指向foo2
的末尾,而不是foo
,因此您的迭代器将从foo
的开头开始,并且当它到达foo2
末尾时结束,这永远不会,因为您正在迭代foo
。一旦it
迭代超过foo
的末尾,您将得到一个段错误。注意:我假设您的意思是编写
++it
,而不是++foo
。Yes it is allowed (i.e. will compile).
No it will not work correctly.
foo2_end
points to the end offoo2
, notfoo
, so your iterator will start at the start offoo
and end when it reaches the end offoo2
, which will be never, because you are iteratingfoo
. Onceit
iterates past the end offoo
you will get a seg-fault.Note: I assumed that you meant to write
++it
, not++foo
.它将编译但会导致段错误。迭代器是特定于对象的,比较来自不同对象的两个迭代器总是会产生不等式。因此,
it != foo2_end
表达式将始终计算为 true,并且当it
到达foo.end()
并且您尝试时,您的程序将崩溃取消引用它。It will compile but result in a seg fault. The iterators are object-specific, and comparing two iterators from different objects will always yield an inequality. So the
it != foo2_end
expression will always evaluate to true, and your program will crash whenit
reachesfoo.end()
and you attempt to dereference it.