词频统计与排序(三)

C++/STL/Map容器实现

Posted by Jack on October 12, 2010

采用STL中的Map容器实现词频统计与排序,代码如下:

#include <iostream>  
#include <string>  
#include <map>  
  
  
using namespace std;  
  
  
// 引入了map  
int main()  
{  
    // 输入  
    string strInput = "我 爱 吃 苹果 , 我 更 爱 吃 香蕉 。 ";  
  
  
    map<string, int> mapWords; // 存放词以及频率  
    unsigned int pos1 = 0;  
    unsigned int pos2 = 0;  
    pos2 = strInput.find(" ", pos1);  
    string strWord;  
    while(pos2 != string::npos)  
    {  
        strWord = strInput.substr(pos1, pos2 - pos1);  
        mapWords[strWord]++;  
        pos1 = pos2 + 1;  
        pos2 = strInput.find(" ", pos1);  
    }  
  
  
    // 在屏幕上进行打印  
    map<string, int>::iterator iter = 0;  
    for(iter = mapWords.begin(); iter != mapWords.end(); ++iter)  
    {  
        cout << iter->first << "     "  
             << iter->second << endl;  
    }  
  
  
    return 0;  
}