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

相关推荐
lly2024064 分钟前
C++ 数组
开发语言
csbysj202018 分钟前
C 强制类型转换
开发语言
m0_6265352019 分钟前
代码分析
开发语言·c#
q***37521 分钟前
QoS质量配置
开发语言·智能路由器·php
__BMGT()25 分钟前
参考文章资源记录
开发语言·c++·qt
一晌小贪欢28 分钟前
【Python办公】用 Selenium 自动化网页批量录入
开发语言·python·selenium·自动化·python3·python学习·网页自动化
ouliten31 分钟前
C++笔记:std::string_view
开发语言·c++·笔记
玫瑰花店42 分钟前
万字C++中锁机制和内存序详解
开发语言·c++·算法
D_evil__1 小时前
[C++高频精进] 文件IO:文件流
c++
西幻凌云1 小时前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器