gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:34:41 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com