c ++类中的向量初始化失败

时间:2017-04-05 02:38:09

标签: c++

我试图为哈希表构建一个构造函数,但它失败了。 任何人都可以告诉我构造函数代码有什么问题吗?

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct node {
string s;
node* next;
};

class QueryProcessor{

int bucket_count;
vector<node*> elems;

explicit QueryProcessor(int bucket_count) : bucket_count(bucket_count), elems(bucket_count) {
    for (int i = 0; i < bucket_count; ++i) {
        elems[i]->s = " ";
        elems[i]->next = NULL;
    }
} 
};

int main(){
int bucket_count;
cin >> bucket_count;
QueryProcessor proc(bucket_count);
}

1 个答案:

答案 0 :(得分:0)

你将elems声明为指向节点的指针的向量,但你实际上从未为它们删除任何内存;所以我认为你实际上是解除引用NULL指针 - 因此它失败了。切断内存或使elems成为一个只有节点的向量。

#include <vector>
#include <iostream>

struct node {
    std::string s;
    node* next;
};

int main() 
{
    // Constructs the container with 5 copies of a pointer to a node- note no actual memory is given to them yet.
    std::vector<node*> elems(5); // efectivly the same as your initalizer list for elems(bucket_count)
    std::cout<<"Size is: "<<elems.size()<<std::endl;
    if(elems[0] == NULL)
    {
        std::cout<<"elems[0] is a null pointer so dont use it!"<<std::endl;
    }
    else
    {
        std::cout<<"elems[0] has the string: "<< elems[0]->s <<std::endl;
    }
}