c++ - 比较来自不同容器的迭代器

标签 c++ stl comparison iterator

比较来自不同容器的迭代器是否合法?

std::vector<int> foo;
std::vector<int> bar;

表达式 foo.begin() == bar.begin() 会产生错误或未定义的行为吗?

(我正在编写一个自定义迭代器,并在实现 operator== 时偶然发现了这个问题。)

最佳答案

如果你考虑 C++11 标准 (n3337):

§ 24.2.1 — [iterator.requirements.general#6]

An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to elements of the same sequence.

§ 24.2.5 — [forward.iterators#2]

The domain of == for forward iterators is that of iterators over the same underlying sequence.

鉴于 RandomAccessIterator 必须满足 ForwardIterator 提出的所有要求,因此未定义比较来自不同容器的迭代器。

LWG issue #446专门讨论了这个问题,建议在标准中添加以下文本(感谢 @Lightness Races in Orbit 引起注意):

The result of directly or indirectly evaluating any comparison function or the binary - operator with two iterator values as arguments that were obtained from two different ranges r1 and r2 (including their past-the-end values) which are not subranges of one common range is undefined, unless explicitly described otherwise.

关于c++ - 比较来自不同容器的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657513/

相关文章:

c++ - 通过 select() 实现非阻塞 udp 套接字

c# - 从 C++ 调用 C#,返回值

c++ - 为什么需要间接寻址

c++ - OpenCV 在新图像中旋转、扭曲和平移 ROI

c++ - C++ vector<bool>的内存分配

r - 比较字符串和数字

c# - 日期时间比较精度

c++ - STL 算法的反向迭代

c++ - const vector 中的非常量

Javascript 比较 localStorage 的 2 个检查