有没有人看到我下面的扩展函数有明显的错误?我包含了类的私有(private)部分和我的 vertex_node 结构以提供一些上下文。我不确定为什么它不能正常扩展。任何帮助,将不胜感激。
private:
//list is pointers to vertex nodes;
struct vertex_node {
string name;
set <string> edges;
};
vertex_node **list;
void Graph:: expand()
{
int new_cap = capacity * 2+1;
//creates new larger array
vertex_node **larger_array = new vertex_node*[new_cap];
//loop through all elements of old array
for(int i = 0; i<capacity; i++){
if(list[i] != NULL){
//rehash each element and place it in new array
int a = hash_string(list[i]->name) % new_cap;
larger_array[a] = new vertex_node;
larger_array[a]->name = list[i] -> name;
larger_array[a]->edges = list[i] -> edges;
}
//delete old list
delete[] list;
list = larger_array;
capacity = new_cap;
}
}
最佳答案
正如我在上面的评论中提到的,您在第一次迭代结束时使整个数组无效。您为避免内存泄漏所做的尝试值得称赞,但必须在两个地方完成。
for(int i = 0; i<capacity; i++){
if(list[i] != NULL){
//rehash each element and place it in new array
int a = hash_string(list[i]->name) % new_cap;
larger_array[a] = new vertex_node;
larger_array[a]->name = list[i] -> name;
larger_array[a]->edges = list[i] -> edges;
}
//clean up every memory location once you're done with it
delete list[i];
list = larger_array;
capacity = new_cap;
}
//clean the whole array at the very end
delete[] list;
关于c++ - Expand 函数未针对我的 Graph 正确扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36705689/