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> 的第二个值的大小从大往小降序排序的。

相关推荐
wjs20243 小时前
Django Nginx+uWSGI 安装配置指南
开发语言
七夜zippoe4 小时前
JVM类加载机制(Class Loading)详解:双亲委派模型与破坏实践
java·开发语言·jvm·类加载·双亲委派
曹牧4 小时前
C#:无法从方法组转换为objec
开发语言·c#
自动化代码美学4 小时前
【Python3.13】官网学习之控制流
开发语言·windows·python·学习
AA陈超5 小时前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
coderxiaohan6 小时前
【C++】仿函数 + 模板进阶
开发语言·c++
IMPYLH6 小时前
Lua 的 collectgarbage 函数
开发语言·笔记·junit·单元测试·lua
百锦再7 小时前
第18章 高级特征
android·java·开发语言·后端·python·rust·django
Tony Bai7 小时前
Go 在 Web3 的统治力:2025 年架构与生态综述
开发语言·后端·架构·golang·web3