使用迭代器从STL列表中删除c++结构

Delete C++ structure from STL list using iterator

本文关键字:删除 c++ 结构 列表 STL 迭代器      更新时间:2023-10-16

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

#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++;
}

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

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_back或pop_front成员函数

当您这样做时,您正在使用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;
}

使用list.erase但你实际上是在用非c++的方式。你不需要用new分配int[5]。写int[5]可以满足你的要求。用c-way定义的Node类型。在c++中,你不需要用typedef

来包装它