您的位置:首页 > 编程语言 > C语言/C++

C++从一个文件中统计所有出现过的单词,并按次数从大到小输出

2013-11-21 17:15 579 查看
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <algorithm>

using namespace std;

int main()
{
ifstream input;
input.open("word.txt");
string eachline;
map<string, int> mapA; //第一个存单词,第二个存单词出现的次数;

while (getline(input, eachline))
{
string::size_type start = 0;
string::size_type end = eachline.find_first_of(" ");
while (end != string::npos) //npos就是这一行到头啦;
{
string content = eachline.substr(start, end - start);
map<string, int>::iterator it = mapA.find(content);
if (it == mapA.end())
{
mapA.insert(pair<string, int>(content, 1));//赋值的时候只接受pair类型;
} else
{
++it->second;

}
start = end + 1;
end = eachline.find_first_of(" ", start);
}

}
multimap<int, string, greater<int> > mapB;

for (map<string, int>::iterator it1 = mapA.begin(); it1 != mapA.end();++it1)
{
mapB.insert(pair<int, string>(it1->second, it1->first));
}

for (map<int, string>::iterator it2 = mapB.begin(); it2 != mapB.end();++it2)
{
//		if ((it2->first) > 1)
cout << it2->second << "单词出现的次数是" << it2->first << endl;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐