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

相关推荐
沐知全栈开发4 小时前
HTML5 浏览器支持
开发语言
wasp5204 小时前
AgentScope Java 核心架构深度解析
java·开发语言·人工智能·架构·agentscope
WHOVENLY4 小时前
【javaScript】- 笔试题合集(长期更新,建议收藏,目前已更新至31题)
开发语言·前端·javascript
慌糖4 小时前
流-为序列化解释
开发语言
LXS_3575 小时前
Day 18 C++提高 之 STL常用容器(string、vector、deque)
开发语言·c++·笔记·学习方法·改行学it
王琦03186 小时前
Python 函数详解
开发语言·python
胡伯来了6 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…6 小时前
Python 中的多层继承
开发语言·python
deng-c-f6 小时前
Linux C/C++ 学习日记(53):原子操作(二):实现shared_ptr
开发语言·c++·学习
wanghowie6 小时前
01.07 Java基础篇|函数式编程与语言新特性总览
java·开发语言·面试