#include <iostream> #include <algorithm> #include <string> #include <cctype> #include <map> #include <vector> using namespace std; struct compare { bool operator()(pair<string, int> p1, pair<string, int> p2) { return p1.second > p2.second; } }; int main() { //读取句子,并将所有字母转化成小写 string sentence; getline(cin, sentence); for (auto& ch : sentence) { if (isalpha(ch)) { ch = tolower(ch); } } //统计单词次数 map<string, int> countMap; auto it = sentence.begin(); while (it != sentence.end()) { string::iterator it2; if (isalpha(*it)) { it2 = it + 1; while (it2 != sentence.end() && isalpha(*it2)) { ++it2; } string tmp(it, it2); countMap[tmp]++; } if (it2 == sentence.end()) { break; } it = it2 + 1; } vector<pair<string, int>> vp(countMap.begin(), countMap.end()); sort(vp.begin(), vp.end(), compare()); for (const auto& e : vp) { cout << e.first << ":" << e.second << endl; } return 0; }
第一步:
首先要读取数据,但是因为一段句子中可能有空格,而直接用cin的话会以空格为分隔符,读不到空格后面的句子,所以我们要用string的专用输入getline来读取句子,它以换行为分隔符。
第二步:
因为要求不区分大小写,所以我们先可以对已有的句子进行处理,如果是字母的话,我们就将其转换成小写。
第三步:
遍历string,从开始位置开始遍历,直到第一个不是字母的位置,用这两个位置的迭代器创建一个string对象——这就是一个单词,然后借助map<string,int>来统计这个单词,map[string]++。如果string存在,则++,如果string不存在,先插入,再++。
第四步:
排序,因为map不支持排序,所以我们将其放到一个vector中,然后排序,注意因为pair支持的比较与我们想要的不符,所以我们要自己写一个仿函数,用来实现比较逻辑。
第五步:
打印这个vector即可