c++ - Expand 函数未针对我的 Graph 正确扩展

标签 c++ graph expand

有没有人看到我下面的扩展函数有明显的错误?我包含了类的私有(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/

相关文章:

c++ - 从按位或组合确定原始常数

c++ - GCC 没有链接到 libstdc++?

c++ - 如何将字符串流中的数据打印到文件中?

具有可移动节点、可访问属性和可靠 ID 的 C++ 图形

java - J树 : Why does my directory don't appear like a directory?

c++ - 错误-根据g++未声明继承的类字段

algorithm - 测量 "heavily linked"节点在图中的表现

python - Tensorflow:tf.identity 和 '=' 运算符有什么区别

r - 基于 R 中的日期列使用连续日期扩展数据框

html - 侧边栏不展开到底部