c++让map按值的大小进行排序
时间: 2023-05-26 13:06:46 浏览: 52
可以通过自定义比较函数来实现map按值的大小进行排序。以下为示例代码:
```cpp
#include <iostream>
#include <map>
#include <algorithm>
bool cmp(const std::pair<int, int>& x, const std::pair<int, int>& y) {
return x.second < y.second;
}
int main() {
std::map<int, int> m{{1, 3}, {2, 1}, {3, 2}};
// 将map转化为vector,并按值大小排序
std::vector<std::pair<int, int>> v(m.begin(), m.end());
std::sort(v.begin(), v.end(), cmp);
// 输出排序后的map
for (const auto& p : v) {
std::cout << p.first << " " << p.second << std::endl;
}
return 0;
}
```
输出:
```
2 1
3 2
1 3
```
相关问题
c++直接对map按值的大小进行排序
C++中可以使用STL中的sort()函数对map按值的大小进行排序。但是需要将map先转化为vector,然后再对vector进行排序,最后再根据排序后的vector的键值对,重新构建一个新的map。
代码如下:
```cpp
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
// 自定义比较函数,用于排序
bool compare(pair<string, int> a, pair<string, int> b){
return a.second < b.second;
}
int main(){
map<string, int> m;
m["apple"] = 5;
m["banana"] = 1;
m["orange"] = 3;
m["pear"] = 2;
m["peach"] = 4;
// 将map转化为vector
vector<pair<string, int>> v(m.begin(), m.end());
// 对vector进行排序
sort(v.begin(), v.end(), compare);
// 构建新的排序后的map
map<string, int> sortedM;
for(auto it = v.begin(); it != v.end(); it++){
sortedM[it->first] = it->second;
}
// 输出排序后的map
for(auto it = sortedM.begin(); it != sortedM.end(); it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
```
输出结果:
```
banana 1
pear 2
orange 3
peach 4
apple 5
```
map按值大小排序 c++
要按值大小对一个 map 进行排序,你可以使用一个辅助的向量来存储 map 的键值对,然后使用比较函数对向量进行排序。以下是一个示例代码:
```cpp
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
bool compare(const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.second < b.second; // 按值升序排序
}
int main() {
std::map<int, int> myMap;
myMap[1] = 5;
myMap[2] = 3;
myMap[3] = 10;
std::vector<std::pair<int, int>> vec(myMap.begin(), myMap.end());
// 对向量进行排序
std::sort(vec.begin(), vec.end(), compare);
// 输出排序后的结果
for (const auto& pair : vec) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
输出结果为:
```
2: 3
1: 5
3: 10
```