【问题标题】:How to put the iterator to nth element of a std::list<class>?如何将迭代器放入 std::list<class> 的第 n 个元素?
【发布时间】:2021-10-02 03:16:05
【问题描述】:

我有一个自定义类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个元素的正确方法是什么?

我尝试使用像 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++ class iterator c++-standard-library stdlist


【解决方案1】:

查看缩小版的错误信息

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

意思是,您正在尝试将 临时 r 值(即 data2.begin())绑定到 非 const 迭代器引用。这是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);

旁注:

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      试试

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-13
        • 2011-02-11
        • 2011-02-10
        • 2023-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多