#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
// 按照value排序的函数
bool compare(const pair<int, string>& a, const pair<int, string>& b) {
return a.second < b.second;
}
int main() {
// 创建一个map,键为int类型,值为string类型
map<int, string> myMap = {
{1, "apple"},
{3, "banana"},
{2, "cherry"}
};
// 将map中的元素拷贝到一个vector中
vector<pair<int, string>> vec(myMap.begin(), myMap.end());
// 使用自定义的比较函数对vector进行排序
sort(vec.begin(), vec.end(), compare);
// 输出排序后的结果
cout << "Sorted map by value:" << endl;
for (auto& p : vec) {
cout << p.first << ": " << p.second << endl;
}
return 0;
}
map<int, string>
,其中键是整数类型,值是字符串类型。map
本身是按键排序的,如果我们想按值排序,则需要将map
中的元素拷贝到一个vector
中。compare
的函数,用于比较两个pair<int, string>
类型的元素,并根据值(即second
)进行排序。std::sort
函数和自定义的比较函数对vector
进行排序。vector
并输出每个元素。如果你希望直接在map
中按键排序,那么不需要额外的操作,因为map
默认就是按键排序的。
上一篇:c++ rtti
下一篇:c++ 获取文件大小
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站