c++ - Iter 类的 operator!= 实现

标签 c++ c++11

基于Iter的实现, 我很难理解 operator!= 并且不明白为什么它不检查 _p_vec?

这是 operator!= 的建议实现,它只比较 _pos

class Iter
{
    public:
    Iter (const IntVector* p_vec, int pos)
        : _pos( pos )
        , _p_vec( p_vec )
    { }

    // these three methods form the basis of an iterator for use with
    // a range-based for loop
    bool operator!= (const Iter& other) const
    {
        return _pos != other._pos;
    }
    ...
    ...
    private:
        int _pos;
        const IntVector *_p_vec;
};

不过,我认为正确的做法如下。换句话说,我们必须比较 _pos_p_vec

bool Iter::operator!= (const Iter& other) const
{
    return _p_vec != other._p_vec || _pos != other._pos;
}

问题>谁的代码是正确的?

===更新 std::vector 如何处理迭代器的比较====

std::vector<int> vecOne { 1, 2, 3};
std::vector<int> vecTwo { 4, 5, 6};

auto iterOne = vecOne.begin();
std::advance(iterOne, 1);

auto iterTwo = vecTwo.begin();
std::advance(iterTwo, 1);

if ( iterOne == iterTwo)
    std::cout << "iterOne == iterTwo" << std::endl;
else
    std::cout << "iterOne != iterTwo" << std::endl;

输出是:iterOne != iterTwo

但是,

std::vector<int> foo;
std::vector<int> bar;

if ( foo.begin() == bar.begin() )
    std::cout << "foo.begin() == bar.begin()" << std::endl;
else
    std::cout << "foo.begin() != bar.begin()" << std::endl;

输出是:foo.begin() == bar.begin()

海湾合作委员会(4.7.1 版)

最佳答案

比较底层容器引用也是一项改进,以确保例如两个不同容器的 begin() 迭代器比较相等。

然而,不同容器的迭代器很少被比较(当使用STL算法时,他们永远不会)。所以这可能被认为是一种优化。想一想您从 begin() 步进到 end() 的循环,因此您要比较的唯一迭代器是“当前”迭代器和 end( ),属于同一个容器。

比较标准容器( vector 等)的迭代器被认为是未定义的行为。事实上,由于它们永远不会在(好的)代码(例如标准算法)中进行比较,因此不必为这种情况定义行为。

所以这个 Iter 类的作者可能还想回到这一点并说:“比较不同 vector 的迭代器是未定义的行为。”

话虽这么说,如果您想确保永远不会比较不同容器的迭代器,请忽略此检查并可能为调试版本断言它(但不要在发布版本中检查它)。

您可能想要比较不同容器的迭代器的一个很好的例子是链表,您将列表的末尾定义为空指针(或指向静态空项实例的指针)。将迭代器视为指向链表项的指针;在这种情况下,end() 迭代器只是一个空指针(或指向这个空项)。它对所有容器都是一样的,因此在这种情况下您不能在比较方法中实现检查。也许这就是为什么没有定义这种比较的原因之一——当比较不同列表的结束迭代器时,它应该返回“不相等”,但它不能 .

关于c++ - Iter 类的 operator!= 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14650164/

相关文章:

c++ - 使用 libpng 调整图像列表的大小(双三次)

c++ - 带有 this 的非静态 void 成员指针函数的 vector

c++ - 我需要知道什么才能开始用 C++/其他语言编写合成器程序?

c++ - 变量自动分配

c++ - 为什么在类定义中定义友元函数

c++11 - 禁用 gcc 中的覆盖检查

c++ - this_thread::sleep_for 和 C++11 标准指定的计时时钟之间的关系吗?

c++ - 传递捕获 unique_ptr 的 lambda

c++ - C++11 中的定时器,带 chrono : from nanoseconds to milliseconds

c++ - 由于对模板化类型的通用(前向)引用而无法实例化函数模板