如何对<string, int>类型的vector按第二个整数元素降序排序?
按词频降序排序单词统计结果
你的核心需求是把存储单词和词频的vector<pair<string, int>>按词频从高到低排序,原代码里的sort调用存在两个问题:
- 语法错误:
sort(vector.begin(), vector.end() greater<int>());中vector.end()和greater<int>()之间缺少逗号; - 逻辑错误:
greater<int>()无法直接用于pair<string, int>类型元素,因为pair默认比较规则是先对比第一个元素(字符串),再对比第二个,而你需要优先按第二个元素(词频)排序。
修正方案
最简洁的方式是使用C11及以上支持的lambda表达式指定排序规则,同时注意不要用vector作为变量名(这是C关键字),以下是修正后的完整代码:
#include <iostream> #include <fstream> #include <map> #include <algorithm> #include <vector> #include <iterator> using namespace std; int main(){ fstream fs; fs.open("/Users/brah79/Downloads/skola/c++/codeTest/test.txt"); string word; map<string, int> word_map; while(fs >> word){ word_map[word]++; // 无需提前find,map不存在key时会默认初始化0,直接++即可完成统计 } vector<pair<string, int>> word_counts(word_map.begin(), word_map.end()); // 用lambda指定排序规则:按词频降序排列 sort(word_counts.begin(), word_counts.end(), [](const pair<string, int>& a, const pair<string, int>& b) { return a.second > b.second; }); for(const auto& item : word_counts){ // 范围for循环遍历更简洁直观 if(item.second == 1){ cout << item.first << " is repeated " << item.second << " time" << endl; } else{ cout << item.first << " is repeated " << item.second << " times" << endl; } } return 0; }
额外优化说明
- 统计词频时直接使用
word_map[word]++,省略了冗余的find判断,逻辑和原代码一致但更简洁; - 遍历vector时改用范围for循环(C++11+),比下标遍历更清晰易读。
内容的提问来源于stack exchange,提问作者brah79
相关产品推荐
相关产品推荐

