const_iterator 与迭代器的比较是否定义明确?

Is comparison of const_iterator with iterator well-defined?(const_iterator 与迭代器的比较是否定义明确?)
本文介绍了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 一样工作.但它实际上是根据标准明确定义的吗?iteratorconst_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

其中 ij 表示容器的 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 与迭代器的比较是否定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)