2013-10-11 44 views
-1

我正在創建一種非常粗糙的hashtable。它將讀取一個ASCII文本文件,並將所有單詞存儲在一個鏈表中以及該單詞被找到的行號上。它使用單詞的第一個字母的數字值來查找存儲該單詞的列表,然後在該列表中搜索該單詞的任何條目,如果未找到任何條目,則向該列表添加新條目,否則將行號碼到匹配的條目。我只是不知道如何初始化vector。它需要128個列表(每個ASCII值一個)。如何初始化對象列表的向量。混淆我知道

另外請注意,我不能夠使用std::map

我知道有INTS的載體,你可以做vector<int> vector_name(128,0)獲得128名所有值爲0的條目基本上我想這樣做,但128空列表entry's。

這裏是我的代碼到目前爲止

#include <iostream> 
#include <vector> 
#include <cstdlib> 
#include <string> 
#include <list> 
#include <algorithm> 
using namespace std; 

class index_table { 
    public: 
     void insert(string key, int value); 
     vector<int>& find(string key); 
    private: 

     class entry{ 
      public: 
       string word; 
       list<int> line_numbers; 
     }; 

     vector<list<entry> > table; 
}; 

int main(){ 
    return 0; 
} 
+0

我會用地圖,其實這是一個分配和它有如何存儲數據,這些具體說明。 –

+2

初始化或分配?哪個版本的C++?現代C++支持初始化,較老的C++在矢量初始化時很麻煩。 –

+0

我想你可以使用'std :: vector >'它在迭代時應該像'std :: map '一樣工作。 – Havenard

回答

0

在你還沒有,你可以做的構造:table.resize(128);現在tableentry對象128空std::list的一個載體。

class index_table { 
public: 
    void insert(string key, int value); 
    vector<int>& find(string key); 

    //My ctor 
    index_table(size_t len) : table(len), len(len) 
    { 
     //some other stuff someday 
    } 

private: 

    //not sure why you want to make entry private but ok... 
    class entry{ 
     public: 
      string word; 
      list<int> line_numbers; 
    }; 

    //some typename convenience for your iterators 
    typedef entrylist list<entry>; 
    typedef entrytable vector<entrylist>; 
    entrytable table; 
}; 
+0

所以如果我想檢查一個值,我可以做 table [2] .entry.word?。 –

+0

你能澄清你的意思嗎?檢查一個值? 'table [i]'會返回給你一個對第i個入口對象列表 – UpAndAdam

+0

的引用,就像我需要比較入口對象中的單詞的值一樣。或者直接訪問它。 –