首页 > 解决方案 > 如何将迭代器放入 std::list 的第 n 个元素?

问题描述

我有一个自定义类MyData

class MyData
{
private:
    int data;

public:
    int getData() const
    {
        return data;
    }

    MyData(int val)
        : data(val)
    {
        cout << "Constructor invoked" << endl;
    }

    MyData(const MyData& other)
    {
        cout << "Copy constructor invoked" << endl;
        data = other.data;
    }

    MyData& operator =(const MyData& other)
    {
        cout << "Assignment operator invoked" << endl;
        data = other.data;
        return *this;
    }

    friend ostream& operator<<(ostream& os, const MyData& d)
    {
        cout << "<< operator overloaded" << endl;
        os << d.data;
        return os;
    }
};

在我的main职能中,我有

list<MyData> data2{ 12,21,32,113,13,131,31 };

++我希望我的迭代器到第 4 个元素,让我们直接说,而不是每次都进行增量操作。

我该怎么做?

list<MyData>::iterator it = data2.begin();
it += 4; // error since I cannot increment this???-compile time error.

我正在这样做-

it++; it++; it++; it++; 

使迭代器直接指向第 4 个元素的正确方法是什么?

我尝试使用Advance like std::advance(data2.begin(),3);. 但是,这会引发错误说

error: cannot bind non-const lvalue reference of type ‘std::_List_iterator<MyData>&’ to an rvalue of type ‘std::__cxx11::list<MyData>::iterator’ {aka ‘std::_List_iterator<MyData>’}
   data1.splice(it, data2,advance(data2.begin(),3),data2.end()); //splice transfer range.

基本上,我这样做是为了将另一个列表与一个元素或某个时间范围拼接起来。

标签: c++classiteratorc++-standard-librarystdlist

解决方案


查看错误消息的简化版本

cannot bind non-const lvalue reference of type [...]
      to an rvalue of type [...]

意思是,您正在尝试将临时 r 值(即data2.begin())绑定到非常量迭代器引用。根据 C++ 标准,这是不可能的。因此,编译器错误。

当你看着std::advance签名

template< class InputIt, class Distance >
constexpr void advance(InputIt& it, Distance n); (since C++17)
//                     ^^^^^^^^^^^^

它期望左值输入迭代器类型。

因此,您需要

auto iter = data2.begin(); // l-value input iterator
std::advance(iter, 3);

旁注:


推荐阅读