如何将迭代器放到 std::list<class> 的第 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++; 

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

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

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.

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

解决方法

查看错误信息的简化版本

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

意思是,您正在尝试将 临时 r 值(即 data2.begin())绑定到 非常量迭代器引用。这是not possible as per the C++ standard。因此,编译器错误。

当您查看 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);

附注:

,

试试

auto it = data2.begin();
std::advance(it,3);

您正在尝试修改 begin() 本身,这就是您收到错误的原因。

,

您想要 std::next 而不是 std::advance。后者将修改传入的迭代器。前者会返回一个新的。

auto it = std::next(data2.begin(),3);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...