使用迭代器从STL列表中删除C ++结构 [英] Delete C++ structure from STL list using iterator

查看:132
本文介绍了使用迭代器从STL列表中删除C ++结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this test program. I don't know how to delete struct in the list using iterator.

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



我知道如何分别删除struct。它是这样的:

I know how to delete the struct separately. It's like this:

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

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

被推回到列表中,我不知道如何根据列表迭代器删除它。

However, when it is pushed back into list, I don't know how to delete it according to the list iterator.

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

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

    lt++;
}


推荐答案

list

nlist.push_back(*p)

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

it is actually creating a Node() and copying the data from the node you just dynamically allocated but not using the actual pointer. And then you try to delete a pointer from the object that the system will automatically delete:

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

您需要声明列表,如 list< Node *> ,以便将指针插入列表。虽然你不应该真正处理这种在c ++中的分配,有几个修改你的代码应该工作:

You need to declare the list like list<Node*> so that the pointer is inserted into the list. Although you should not really deal with this kind of allocation in c++, with a couple of modifications your code should work:

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

这篇关于使用迭代器从STL列表中删除C ++结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆