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 天前
C++笔记——STL map
c++·笔记
独隅1 天前
在 Lua 中,你可以使用 `os.date()` 函数轻松地将时间戳转换为格式化的时间字符串
开发语言·lua
思麟呀1 天前
Linux的基础IO流
linux·运维·服务器·开发语言·c++
星释1 天前
Rust 练习册 :Pythagorean Triplet与数学算法
开发语言·算法·rust
星释1 天前
Rust 练习册 :Nth Prime与素数算法
开发语言·算法·rust
lkbhua莱克瓦241 天前
Java基础——集合进阶3
java·开发语言·笔记
多喝开水少熬夜1 天前
Trie树相关算法题java实现
java·开发语言·算法
QT 小鲜肉1 天前
【QT/C++】Qt定时器QTimer类的实现方法详解(超详细)
开发语言·数据库·c++·笔记·qt·学习
WBluuue1 天前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
lsx2024061 天前
MySQL WHERE 子句详解
开发语言