将数据从迭代器插入到列表中的问题

Issue with inserting data from an iterator into a list

本文关键字:列表 问题 插入 数据 迭代器      更新时间:2023-10-16

我有两组非常相似的代码。我想强调的是,它们不是按顺序排列的,甚至不在同一个程序中。为了便于说明,我把它们并排放在一起:

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.