比较来自不同容器的迭代器

2022-01-07 00:00:00 comparison iterator c++ stl

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

std::vector富;std::vector酒吧;

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

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

解决方案

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

<块引用>

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

迭代器 j 被称为可从迭代器 i 到达当且仅当存在表达式 ++i 这使得 i == j.如果 j 可从 i 到达,则它们引用相同序列的元素.

<块引用>

§24.2.5 —[forward.iterators#2]

前向迭代器的==域是相同底层序列上的迭代器的域.

鉴于 RandomAccessIterator 必须满足 ForwardIterator 强加的所有要求,未定义比较来自不同容器的迭代器.

LWG 问题 #446 专门讨论这个问题,建议在标准中添加以下文本(感谢 @Lightness在轨道上进行比赛以引起人们的注意):

<块引用>

直接或间接评估任何比较函数或二元运算符的结果,其中两个迭代器值作为从两个不同范围 r1 和 r2(包括它们的最后值)获得的参数 一个公共范围的子范围未定义,除非另有明确说明.

Is it legal to compare iterators from different containers?

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

Does the expression foo.begin() == bar.begin() yield false or undefined behavior?

(I am writing a custom iterator and stumbled upon this question while implementing operator==.)

解决方案

If you consider the C++11 standard (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.

Given that RandomAccessIterator must satisfy all requirements imposed by ForwardIterator, comparing iterators from different containers is undefined.

The LWG issue #446 talks specifically about this question, and the proposal was to add the following text to the standard (thanks to @Lightness Races in Orbit for bringing it to attention):

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.

相关文章