问题描述
请考虑以下代码:
#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 << "\n";
}
这里我介绍了一个拼写错误:在比较中我调用 vec.end()
而不是 vec.cend()
。这看起来像gcc 5.2一样工作。但是它实际上是根据标准很好地定义的吗?可以安全比较
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没有说你可以将迭代器
与 const_iterator
。这会导致和。现在在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
表示容器的迭代器
类型的对象,或者
都可以由对象容器的 const_iterator
类型引用的语义无变化的相同元素。
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和迭代器的比较明确定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!