2

我有这个测试程序。我不知道如何使用迭代器删除列表中的结构。

#include<iostream>
#include<list>
using namespace std;
typedef struct Node
{
    int * array;
    int id;
}Node;

void main()
{
    list<Node> nlist;
    for(int i=0;i<3;i++)
    {
        Node * p = new Node;//how to delete is later?

        p->array = new int[5];//new array
        memset(p->array,0,5*sizeof(int));

        p->id = i;

        nlist.push_back(*p);//push node into list
    }

    //delete each struct in list
    list<Node>::iterator lt = nlist.begin();
    while( lt != nlist.end())
    {
        delete [] lt->array;

        delete &(*lt);//how to delete the "Node"?

        lt++;
    }
}

我知道如何单独删除结构。就像这样:

Node * p = new Node;
p->array = new int[5];

delete [] p->array; //delete the array
delete p;//delete the struct

但是,当它被推回列表时,我不知道如何根据列表迭代器将其删除。

list<Node>::iterator lt = nlist.begin();
while( lt != nlist.end())
{
    delete [] lt->array;

    delete &(*lt);//how to delete the "Node"?

    lt++;
}
4

3 回答 3

1

您可以使用列表擦除从列表之间的任何位置删除节点。

list<Node>::iterator it = nlist.begin();
advance(it,n); \\n is the node you want to delete, make sure its less than size of list
it = mylist.erase (it); 

或者,如果您想从列表的任一端删除元素,您可以使用 pop_backpop_front成员函数。

于 2012-12-24T07:56:23.850 回答
0

由于您在声明列表list<Node>时使用:

nlist.push_back(*p)

它实际上是创建一个Node()并从您刚刚动态分配但不使用实际指针的节点复制数据。然后你尝试从系统将自动删除的对象中删除一个指针:

delete &(*lt); // this causes double free

您需要像list<Node*>这样声明列表,以便将指针插入到列表中。尽管您不应该真正在 c++ 中处理这种分配,但通过一些修改,您的代码应该可以工作:

int main()
{
  list<Node*> nlist;
  for(int i=0;i<3;i++)
  {
    Node *p = new Node;//how to delete is later?

    p->array = new int[5];//new array
    memset(p->array,0,5*sizeof(int));

    p->id = i;

    nlist.push_back(p);//push node into list
  }

  //delete each struct in list
  list<Node*>::iterator lt = nlist.begin();
  while( lt != nlist.end())
  {
    delete [] (*lt)->array;

    delete *lt;//how to delete the "Node"?

    lt++;
  }

  return 0;
}
于 2012-12-24T07:13:36.790 回答
0

使用list.erase 但你真的是在做那种非 C++ 的方式。您不需要使用 new 分配 int[5]。写 int[5] 做你想做的事。您在 c-way 中定义的节点类型。在 c++ 中,您不需要用 typedef 包装它

于 2012-12-24T07:10:32.853 回答