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.
这篇关于比较来自不同容器的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较来自不同容器的迭代器
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
