繁体   English   中英

通过指针向量删除指针

[英]Deleting pointers through a vector of pointers

因此,我正在研究网络流量问题,必须能够删除二分图的右半部分,以便一次处理多个图。 这是我设置节点和边缘类的方式:

class Node {
public:
    Node();
    int id;
    int visited;
    Node_Type type;
    vector <bool> letters;
    vector <class Edge *> adj; // Adjacency list
    class Edge *backedge;
};

class Edge {
public:
    Node *to;
    Node *from;
    Edge *reverse; // Edge with opposite to/from
    int original; // 1 on normal
    int residual; // 0 on normal
};

在这张图中可以看到一个势能图:

图形图像

我的目标是删除第二列右侧的所有边缘和节点。

我将所有节点组织在一个从左到右/从上到下索引的节点指针向量中,并且我试图遍历该向量并删除第二和第三列内节点邻接表中包含的所有边或第三和第四列。 之后,我将向后遍历并删除接收器节点以及第三列的节点,然后最终调整节点向量的大小以仅容纳节点的前两列。

这是我的做法:

void DeleteHalfGraph() {
    int i, j;

    // Delete all edges between dice, words, and the sink
    for(i = 1; i < nodes.size(); i++) {
        if(nodes[i]->type == DICE) { // DICE refers to the second column of nodes
            for(j = 0; j < nodes[i]->adj.size(); j++) {
                if(nodes[i]->adj[j]->to->type == WORD) {
                // WORD refers to the third column of nodes
                    delete nodes[i]->adj[j];
                }
            }
        }
        else if(nodes[i]->type == WORD || nodes[i]->type == SINK) {
        // SINK refers to the 4th column of nodes
            for(j = 0; j < nodes[i]->adj.size(); j++) {
                delete nodes[i]->adj[j];
            }
        }
    }

    // Delete all nodes now not connected to edges
    // minNodes = 5, size of the vector without the 3rd/4th columns
    for(i = nodes.size() - 1; i >= minNodes; i--) {
        if(nodes[i]->backedge != NULL) delete nodes[i]->backedge;
        delete nodes[i];
    }

    nodes.resize(minNodes);
}

我在编译时遇到的错误是:

*** Error in `./worddice': malloc(): memory corruption (fast): 0x0000000000c69af0 ***

我很可能只是不能正确地理解我的指针,因为最近我还没有处理释放内存的问题。 无论如何,我要去哪里错了? 任何帮助是极大的赞赏。

该解决方案实际上最终变得非常简单:从中删除边后,我并没有调整邻接列表的大小,因此当我去为下一个图形的向量添加新边时,空指针仍将留在那里(我尝试在程序的其他部分进行访问)。 从我的邻接向量中删除那些可以解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM