【发布时间】:2017-04-13 22:45:29
【问题描述】:
所以我正在处理网络流问题,并且必须能够删除我的二分图的右半部分才能一次处理多个图。以下是我设置节点和边缘类的方法:
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
};
在这张图片中可以看到一个潜在的图表:
我的目标是删除第二列右侧的所有边和节点。
我将所有节点组织在节点指针向量中,索引从左到右/从上到下,我正在尝试遍历该向量并删除节点邻接列表中包含的任何边第三列或第三和第四列。之后我将向后遍历并删除 sink 节点以及第三列的节点,然后最后调整节点向量的大小以仅容纳前两列节点。
我是这样做的:
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 ***
我可能没有正确理解我的指针,因为我最近没有处理过这样的释放内存。无论如何,我哪里错了?非常感谢任何帮助。
【问题讨论】:
-
这样的错误通常意味着您在程序早期的某个时间点做了一些未定义的行为,直到现在才检测到。像 valgrind 这样的工具可以帮助识别此类错误。
-
我看到了很多删除,但没有更新...再说一次,我想粘贴那部分可能毫无意义...
-
@EvanCarslake 所以这是我在尝试查找类似问题时看到的。我在 main 中进行了所有新操作,然后调用了这个函数,它实际上是 Graph 类的成员(为了我的问题简单起见,我删除了它)。我正计划尝试将所有新闻传输到 Graph 类构造函数,但我想我会先这样尝试。他们的新闻/删除都必须包含在同一个类中吗?我的印象是,您可以从指向它的任何指针中删除内存。
-
@Toy_Reid 是的,任何你“新”的东西你都可以通过指向它的指针在任何地方一次删除它。
-
@Toy_Reid 他建议你自己做一个穷人的智能指针:当你考虑
delete一个节点时,递减并检查计数器。如果为零,请继续使用delete。当然,这意味着您必须在分配Node时增加计数器。这是practice RAII 和the Rule of Three 并将Node指针包装在计数器对象中并传递计数器对象的绝佳机会。
标签: c++ pointers memory-management network-flow