我有這個測試程序。我不知道如何使用迭代器刪除列表中的結構。使用迭代器從STL列表中刪除C++結構
#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++;
}
爲什麼你動態地分配它呢? – chris
這只是一個例子,我的程序不是這樣的。 – Terry