2013-04-26 227 views
0

我正在嘗試創建一個將文件讀入字符串向量並計算每個唯一單詞出現次數的字典。這是我到目前爲止:計算字符串向量中單詞的出現次數

int main() 
{ 
    ifstream input1; 
    input1.open("Base_text.txt"); 

    vector<string> base_file; 
    vector<int> base_count; 


    if (input1.fail()) 
    { 
     cout<<"Input file 1 opening failed."<<endl; 
     exit(1); 
    } 

    make_dictionary(input1, base_file, base_count); 


} 

void make_dictionary(istream& file, vector<string>& words, vector<int>& count) 
{ 


    string word; 
    int i=0; 

    while (file>>word) 
    { 
     words.push_back(word); 
     cout<<words[i]; 
     i++; 
    } 


    for (i=0; i<words.size(); i++) 
    { 
     if ((words[i+1]!=words[i])) 
      { 
       count.push_back(i); 

      } 
    } 

問題1:如何獲得包含空格和識別單個詞的向量? 問題2:任何想法如何繼續第二部分(for循環)?

+0

你可以使用提升? – 2013-04-26 21:47:17

+0

[計數每個單詞在文件中出現的次數]可能的重複(http://stackoverflow.com/questions/6103927/count-the-number-of-times-each-word-occurs-in-a-文件) – 2013-04-26 22:05:16

回答

5

這是非常低效的。您應該使用

std::map<string, int> 

改爲。它既簡單又有效。

循環遍歷文件。當你看到一個單詞時,看看它是否在地圖上。如果不是,請添加一個帶有計數1的新單詞。如果是,則增加計數。

+0

它甚至不必那麼複雜'std :: map 字典; ... ++詞典[單詞];''是你所需要的。 – john 2013-04-26 22:00:49

+0

雖然operator []插入新元素時,不知道int值是否會初始化爲0。 – 2013-04-26 22:05:52

+0

它會保證,不要問我引用標準。 – john 2013-04-26 22:07:33

相關問題