2017-04-05 40 views
-2

我試圖爲散列表構建一個構造函數,但失敗了。 任何人都可以告訴我構造函數代碼有什麼問題嗎?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

'elems(bucket_count)',請注意vector中的所有'bucket_count'元素都是空指針。 – songyuanyao

+0

未在您的代碼中看到任何錯誤。編譯器說了什麼? –

+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; 
    } 
} 
+0

謝謝你的解決方案。我想我沒有清楚我的代碼,所以我更新了我的代碼。編譯器說:'拋出的異常:讀取訪問衝突。' –

+0

所以我不認爲你所做的更新是非常正確的,因爲ctor是有效的私人。這是我所指的一個例子,如果你想保留一個指針向量。 明確QueryProcessor(INT BUCKET_COUNT):BUCKET_COUNT(BUCKET_COUNT),elems的(BUCKET_COUNT){ 對(INT I = 0;我 s <<「ptr:」< next << endl; } else { cout <<「initg node:」<< i << endl; elems [i] - > s =「」; elems [i] - > next = NULL; } } } –