问题描述
比较来自不同容器的迭代器是否合法?
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.
这篇关于比较来自不同容器的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)