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 与迭代器的比较是否定义明确?
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
