C++11 中的尾端迭代器失效

Past-the-end iterator invalidation in C++11(C++11 中的尾端迭代器失效)

本文介绍了C++11 中的尾端迭代器失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 上最受欢迎的帖子 迭代器失效规则 声称不清楚是否过去的迭代器 (即 end()cend()rend()crend() 返回的那些)根据与指向容器中元素的普通迭代器相同的规则使其失效.这些声明适用于 2003 年和 2011 年 C++,请参阅讨论结束迭代器无效规则的帖子,其中接受的答案表明2003 年的标准在这个问题上是模棱两可的.这个结论基于 23.1/10 中的评论(在 swap() 的上下文中),这似乎暗示当规范没有明确提到过去迭代器的失效时,它们可能作废.

The most popular post on C++ Iterator invalidation rules claims that it's not clear if the past-the-end iterators (i.e., those returned by end(), cend(), rend(), and crend()) are invalidated according to the same rules as normal iterators, which point to elements in the container. These claims, made for both 2003 and 2011 C++, defer to a post discussing End iterator invalidation rules, where the accepted answer suggests that the 2003 standard is ambiguous on the matter. This conclusion is based on a comment in 23.1/10 (in the context of swap()) that seems to imply that when the spec does not explicitly mention invalidation of past-the-end iterators, they may be invalidated.

对该帖子问题的评论(由 mike-seymour 撰写)表明,对于 deques,C++11 在这个问题上是明确的.我的问题是关于所有容器的:

A comment on that post's question (by mike-seymour) suggests that C++11 is unambiguous on this matter, in the case of deques. My question is about all containers:

  • 在 C++11 中,是否有任何容器操作可能使过去的迭代器无效,并且这种行为在语言规范中是模棱两可的?

换个说法,

  • 在执行容器操作后,我是否可以相信过去迭代器的有效性,但并未说它可能会使过去的迭代器失效?

推荐答案

我的问题是关于所有容器的:

My question is about all containers:

  • 在 C++11 中,是否有任何容器操作可能使过去的迭代器无效,并且这种行为在语言规范?

我不确定您所说的这种行为在语言规范中不明确的地方"是什么意思,但肯定有一些操作会使过去的操作符无效(比如插入到 std::vectorstd::string).

I am not sure what you mean with "where this behavior is ambiguous in the language specification", but there certainly are operations that invalidate past-the-end operators (like insert into a std::vector or std::string).

换个说法,

  • 在执行容器操作后,我是否可以相信过去迭代器的有效性,但并未说它可能会失效过去的迭代器?

您可以像任何其他迭代器一样信任过去的迭代器:任何不会(可能)使迭代器无效的操作都不会使它们无效.除了标准可能存在错误之外,所有操作都没有说它们(可能)使操作员无效.

You can trust the past-the-end iterator like any other iterator: Any operation that does not (potentially) invalidate iterators won't invalidate them. Except for the possibility of the standard sporting a bug, that is all operations where it doesn't say that they (potentially) invalidate operators.

这篇关于C++11 中的尾端迭代器失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++11 中的尾端迭代器失效

基础教程推荐