//2021/05/20H:\力扣遇到的题\map的一些操作\map的一些操作.vcxproj
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
void printMap(map<string, int>& wordMap)
{
for (map<string, int>::iterator it = wordMap.begin(); it != wordMap.end(); it++) {
cout << it->first << " " << it->second << endl;
}
}
//使用匿名函数对map的value进行排序
vector<pair<string, int>> sortMapsValue(map<string, int>& wordMap)
{
//转换为pair
vector<pair<string, int>> ret;
for (map<string, int>::iterator it = wordMap.begin(); it != wordMap.end(); it++) {
ret.push_back(*it);
}
//对ret进行排序
sort(ret.begin(), ret.end(), [](const pair<string, int> a, const pair<string, int> b) {
return a.second > b.second;
});
//打印ret
for (vector<pair<string, int>>::iterator it = ret.begin(); it != ret.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
return ret;
}
void test()
{
vector<string> words;
words.push_back("the");
words.push_back("day");
words.push_back("is");
words.push_back("sunny");
words.push_back("the");
words.push_back("the");
words.push_back("the");
words.push_back("sunny");
words.push_back("is");
words.push_back("is");
int wordsNum = words.size();
map<string, int> wordMap;
for (int i = 0; i < wordsNum; i++) {
if (wordMap.count(words[i]) == 0) {
wordMap.insert(pair<string, int>(words[i], 1));
}
else {
wordMap[words[i]]++;
}
}
//打印
printMap(wordMap);
sortMapsValue(wordMap);
}
int main()
{
test();
cout << "hello world!" << endl;
system("pause");
return 0;
}
【C++】对map的value进行排序
最新推荐文章于 2023-11-03 15:44:06 发布