将数据从迭代器插入到列表中的问题
Issue with inserting data from an iterator into a list
我有两组非常相似的代码。我想强调的是,它们不是按顺序排列的,甚至不在同一个程序中。为了便于说明,我把它们并排放在一起:
std::list<int*> bob;
int * j = new int;
*j = 5;
bob.push_front(j);
std::list<int>::const_iterator goop = bob.begin();
bob.push_front(*goop); //takes issue with inserting goop
std::list<int> bob;
j = 5;
bob.push_front(j);
std::list<int>::const_iterator goop = bob.begin();
bob.push_front(*goop); //inserts goop just fine
第一个是指向整型的指针列表,第二个是指向整型的指针列表。第一个问题是我在尝试插入时解引用迭代器,抱怨类型,特别是想要"int * const &"
这是怎么回事?关于迭代器如何引用其底层数据,以及我必须如何执行第二种情况,以便从列表的迭代器插入列表,我误解了什么?
修改如下:
std::list<int>::const_iterator goop = bob.begin();
:
std::list<int*>::const_iterator goop = bob.begin();
由于您希望指针指向整数,在第一个示例中
您正在使用的迭代器是list<int>::const_iterator
,但您正在使用它来迭代list<int*>
。
您将需要使用list<int*>::const_iterator
来迭代list<int*>
。
我不明白你的困惑。list
部分完全无关紧要。你要做的是:
int* j = new int;
int i = j; // illegal, pointer vs integer
j = i; // illegal, integer vs pointer
就是这么简单。
std::list<int*> bob;
bob是指向int
eger值(int*
)的指针的列表。它的值类型是很简单的int*
。
int * j = new int;
j
是一个指向整数的指针
*j = 5;
这一行与问题完全无关。
bob.push_front(j);
这将把最近分配的地址推到列表的前面。不是5,是内存的地址
std::list<int>::const_iterator goop = bob.begin();
goop
是值类型为int
而不是int*
的列表的迭代器,因此这一行不能编译(http://ideone.com/zfmvPR),因为list<int>
和list<int*>
是完全不同的类型。
bob.push_front(*goop); //takes issue with inserting goop
如果前一行已经编译了,这将是非法的,因为*goop
的类型是int
,但bob
的值类型是int*
而不是int
。
bob.push_front
取一个int*
。*goop
将是int
。
也许你应该考虑利用c++ 11中的auto
关键字
std::list<int*> bob;
bob.push_front(new int);
auto it = bob.begin(); // std::list<int*>::iterator it = bob.begin();
// or auto it = bob.cbegin(); if you want a const_iterator
pop.push_front(*it);
但是如果你打算使用c++ 11,并且你的列表负责这些指针的所有权,你可能应该考虑使用std::unique_ptr
,因为你所展示的代码并没有显示delete
的使用。
std::list<unique_ptr<int>> bob;
当你犯这个错误的时候,也更清晰了:
std::list<unique_ptr<int>> bob;
std::list<int> sally; // clearly not compatible with bob.
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- C++关于ENUM的问题。我得到的响应比枚举列表大
- 替代在python中制作邻接列表与图形问题的字典?(如 C++ 中的 vector<vector<int&g
- 在C++中循环访问自定义结构列表的小问题
- 关于Stroustrup C++书的自动和{}列表问题
- 将值推送到 getter 函数调用的列表中时出现问题
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 在 c++ 中访问列表向量时出现问题
- 有关具有编译错误的操纵列表的问题
- C++:继承和列表函数作为类成员的问题
- C++ 入门加列表:10.9 "顶部"指针问题
- STL链接列表问题
- 初始化列表问题
- DirectX 12-命令列表问题
- CreateHwndRenderTarget参数列表问题
- 初始化列表问题,重点是STD向量
- c++初始化列表问题-错误:试图引用已删除的函数
- 特定于对象的数组列表C++问题
- 模板参数列表问题太少
- 又是一个c++列表问题