c++ - vector 迭代器不兼容 : runtime error

标签 c++ iterator

我目前在处理包含对象 vector 的类的析构函数时遇到问题。应用程序运行良好,但在释放堆时会引发错误。

这是我的析构函数的代码:

    ~StaticNetwork(void) { // clear memory
    for(vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); )
        nodes.erase(iter++);
}

节点被添加到网络中如下:

    if((temp = is_already_added(regex_d[1])) >= 0) // check if the src node has already been added
            {
                if((temp1 = is_already_added(regex_d[2])) >= 0) // check if the next_hop has already been added
                {
                    nodes[temp]->add_n_vchannels(regex_d[5]);
                    nodes[temp]->add_next_hop(nodes[temp1]);
                }
                else // the next_hop has not been added 
                {
                    Node *anext_hop = new Node(regex_d[2]);

                    nodes[temp]->add_next_hop(anext_hop);
                    nodes[temp]->add_n_vchannels(regex_d[5]);

                    nodes.push_back(anext_hop); //  add next hop        
                    param.n_of_nodes++;
                }       
            }

网络由指向实际节点的指针组成。

任何帮助/建议/引用/(建设性)批评将不胜感激。

最佳答案

您对容器的迭代是错误的。如果 node 是类的成员,则忽略它,因为 vector 的析构函数会处理它。如果它不是成员并且你真的想删除所有元素,最简单的方法是调用 node.clear() (注意两者等同于你的代码,但如果它会泄漏指向的内存应该由你的类(class)管理)

如果指针由您的类管理,请考虑使用智能指针或特定指针容器。否则,释放所有内存的最简单循环是:

for ( std::vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); ++it )
   delete *it;

请注意,我没有修改容器本身,只是修改了包含的元素。

关于c++ - vector 迭代器不兼容 : runtime error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968120/

相关文章:

c++ - ostream_iterator vs for each 循环效率

c++ - 如何从带有注释的 C++ 数据文件中读取数值(如 Fortran)

c++ - Qt in Visual Studio 2013 with cmake - 我如何让它工作?

java - 如何一次又一次地使用同一个迭代器?

c++ - 使用 STL 和一元函数适配仿函数检查列表成员资格

C++ 多映射迭代器失效

c++ - 将监视器方法作为线程参数传递 c++

c++ - Linux 系统调用 aio_write() 失败,错误代码为 22 (EINVAL)

c++ - 返回 std::tuple 并 move 语义/复制省略

java - 如何使用迭代器复制列表