如何解决如何将迭代器放到 std::list<class> 的第 n 个元素?
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;
}
};
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);
附注:
- 需要了解更多关于c++值类别;请参阅此处Value categories。
-
it+=4;
、it++;
等操作仅适用于 random access iterators (请参阅链接中的 Expression )。但,std::list
有 只有bidirectional iterator, 不支持上述内容。
试试
auto it = data2.begin();
std::advance(it,3);
您正在尝试修改 begin()
本身,这就是您收到错误的原因。
您想要 std::next
而不是 std::advance
。后者将修改传入的迭代器。前者会返回一个新的。
auto it = std::next(data2.begin(),3);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。