展开功能不适合我的图表扩展

时间:2016-04-18 22:56:01

标签: c++ graph expand

有没有人看到下面我的扩展功能出现了明显的错误?我已经包含了类的私有部分和我的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;
    }
}

1 个答案:

答案 0 :(得分:1)

正如我在上面的评论中提到的那样,你在第一次迭代结束时使整个数组失效。您试图避免内存泄漏是值得称道的,但必须在2个地方完成。

    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;