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
j
is called reachable from an iteratori
if and only if there is a finite sequence of applications of the expression++i
that makesi == j
. Ifj
is 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.
这篇关于比较来自不同容器的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较来自不同容器的迭代器
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01