C++:vector中pair的排序方法

前言

有时我们需要往 vector 容器中插入 "键值对(pair<int, int>)" 数据,同时又需要按第二个或者第一个进行排序。如上的问题可以借助 STL 的 sort 完成。

程序

1. 向算法传递函数

static bool cmp(const pair<int, int>& a, const pair<int, int>& b)

{

// 以pair对的第2个数的大小从大往小排序

return a.second > b.second;

}

2. 借助 lambda 表达式

sort(scores.begin(),scores.end(),

\](const pair\\& a, const pair\\& b){ return a.second \> b.second; }); // lambda表达式

3. 完整程序

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

static bool cmp(const pair<int, int>& a, const pair<int, int>& b)

{

// 以pair对的第2个数的大小从大往小排序

return a.second > b.second;

}

int main()

{

vector<pair<int, int> > scores;

scores.push_back(make_pair(1, 3));

scores.push_back(make_pair(2, 1));

scores.push_back(make_pair(3, 2));

cout<<"before sort : "<<endl;

for(int i = 0; i < scores.size(); i++)

{

cout<<scores[i].first<<" "<<scores[i].second<<endl;

}

//sort(scores.begin(), scores.end(), cmp); // 向算法传递函数

sort(scores.begin(),scores.end(), [](const pair<int, int>& a, const pair<int, int>& b){ return a.second > b.second; }); // lambda表达式

cout<<"after sort : "<<endl;

for(int i = 0; i < scores.size(); i++)

{

cout<<scores[i].first<<" "<<scores[i].second<<endl;

}

return 0;

}

结果

下图结果是按 pair<int, int> 的第二个值的大小从大往小降序排序的。

相关推荐
菜菜的院子1 天前
vcpkg配置
c++
lsx2024061 天前
Chart.js 极地图
开发语言
爱吃山竹的大肚肚1 天前
在Java中,从List A中找出List B没有的数据(即求差集)
开发语言·windows·python
weixin_462446231 天前
【原创实践】Python 将 Markdown 文件转换为 Word(docx)完整实现
开发语言·python·word
企微自动化1 天前
企业微信二次开发:深度解析外部群主动推送的实现路径
java·开发语言·企业微信
我的offer在哪里1 天前
c++的回调函数
开发语言·c++
一棵开花的树,枝芽无限靠近你1 天前
【face-api.js】2️⃣ NetInput - 神经网络输入封装类
开发语言·javascript·神经网络
yongche_shi1 天前
第九十九篇:Python在其他领域的应用:游戏开发、物联网、AIoT简介
开发语言·python·物联网·游戏开发·aiot
froginwe111 天前
Node.js 回调函数
开发语言
期待のcode1 天前
Java中的继承
java·开发语言