问题描述
考虑以下代码:
#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 与迭代器的比较是否定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!