c++ - 如何将迭代器放入 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.
基本上,我这样做是为了将另一个列表与一个元素或某个时间范围拼接起来。
解决方案
查看错误消息的简化版本
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);
旁注:
推荐阅读
- asynchronous - 具有异步返回的异步龙卷风服务器
- java - 点被采用是gradle脚本中的正斜杠
- time-complexity - 二维矩阵中 DFS 的时间复杂度(移动是 4 路,每次在当前节点完成 DFS 时我们都会重置访问标志)
- udeploy - 如何在 UCD(UrbanCode Deploy) 中创建可重用组件?
- javascript - Chrome 扩展程序:在执行其他功能之前等待 sendMessage 响应?
- javascript - 使用 Python 从 IMDB 访问 JSON 字典
- java - mariaDB 中二进制匹配的 JPA 方法签名
- nestjs - Nest.js - 导入的服务未被其他服务识别
- r - 带有对象的管道操作 dplyr R 返回了一个列表
- java - 使用 kafka 运行 Spark 流示例时出现 NoSuchMethodError