代码如下:
#include<iostream>
#include<string>
#include<fstream>
#include<map>
#include<iomanip>
#include<algorithm>
#include<vector>int read_file(std::map<std::string,int> &map_words)
{std::string filename = "words.txt";std::fstream fin;fin.open(filename.c_str(), std::ios::in);std::string tmp;while (fin >> tmp){++map_words[tmp];}return 0;
}int save_words(std::multimap<int, std::string, std::less<int>> &multimap_words, std::map<std::string,int> map_words)
{for(std::map<std::string, int>::iterator iter = map_words.begin(); iter != map_words.end(); ++iter)
{multimap_words.insert(std::pair<int, std::string>(iter->second, iter->first));
}return 0;
}int print_words(std::multimap<int, std::string, std::less<int>> multimap_words)
{int i = 0;for(std::multimap<int, std::string>::iterator iter = multimap_words.begin(); (iter != multimap_words.end()); ++iter, ++i){if((iter->first == prev(iter,1)->first) || (i < 20) || 1){std::cout << "第" << i << "个单词,它出现的频次是:" << iter->first << " 它是:" << iter->second << std::endl;}else{break;}}return 0;
}int main(int argc, char* argv[])
{std::map<std::string,int> map_words;read_file(map_words);std::multimap<int, std::string, std::less<int>> multimap_words;save_words(multimap_words,map_words);print_words(multimap_words);return 0;
}
运行程序的结果如下: