Is comparison of const_iterator with iterator well-defined?(const_iterator 与迭代器的比较是否定义明确?)
问题描述
考虑以下代码:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> vec{1,2,3,5};
for(auto it=vec.cbegin();it!=vec.cend();++it)
{
std::cout << *it;
// A typo: end instead of cend
if(next(it)!=vec.end()) std::cout << ",";
}
std::cout << "
";
}
这里我引入了一个错字:在比较中我调用了 vec.end() 而不是 vec.cend().这似乎与 gcc 5.2 一样工作.但它实际上是根据标准明确定义的吗?iterator 和 const_iterator 可以安全地比较吗?
Here I've introduced a typo: in the comparison I called vec.end() instead of vec.cend(). This appears to work as intended with gcc 5.2. But is it actually well-defined according to the Standard? Can iterator and const_iterator be safely compared?
推荐答案
令人惊讶的是,C++98 和 C++11 并没有说可以将 iterator 与 进行比较const_iterator.这导致 LWG 问题 179 和 LWG 问题 2263.现在在 C++14 中,第 23.2.1[container.requirements.general]p7
Surprisingly, C++98 and C++11 didn't say that you can compare a iterator with a const_iterator. This leads to LWG issue 179 and LWG issue 2263. Now in C++14, this is explicitly permitted by § 23.2.1[container.requirements.general]p7
在表达式中
i == j
i != j
i < j
i <= j
i >= j
i > j
i - j
其中 i 和 j 表示容器的 iterator 类型的对象,或者两者都可以被容器的 const_iterator 的对象替换type 引用相同的元素,语义没有变化.
where i and j denote objects of a container's iterator type, either or
both may be replaced by an object of the container's const_iterator
type referring to the same element with no change in semantics.
这篇关于const_iterator 与迭代器的比较是否定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const_iterator 与迭代器的比较是否定义明确?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
