2013-04-26 164 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

相关问题