comparing iterators from different containers(比较来自不同容器的迭代器)
问题描述
比较来自不同容器的迭代器是否合法?
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
jis called reachable from an iteratoriif and only if there is a finite sequence of applications of the expression++ithat makesi == j. Ifjis reachable fromi, 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.
这篇关于比较来自不同容器的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较来自不同容器的迭代器
				
        
 
            
        - 从python回调到c++的选项 2022-11-16
 - 静态初始化顺序失败 2022-01-01
 - STL 中有 dereference_iterator 吗? 2022-01-01
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 - 近似搜索的工作原理 2021-01-01
 - C++ 协变模板 2021-01-01
 - Stroustrup 的 Simple_window.h 2022-01-01
 - 使用/clr 时出现 LNK2022 错误 2022-01-01
 - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 
						
						
						
						
						
				
				
				
				