C++学习笔记(sort排序函数)

1、基本语法

sort函数用法的官方解释: cppreference.com
大致是说,sort函数是定义在std空间中的一个函数。有三个参数,前两个分别是容器的首地址和尾地址(迭代器地址也可以),最后一个是比较器。如果用自定义的比较器,则返回值必须得是bool类型。

2、用法

2.1、基本用法

用官方给出的greater和less对数组进行排序。

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
	int list[10];
	
	for(int i = 0; i < 10 ; i++)
		list[i] = rand();
	
	sort(list, list + 10, greater<int>());			//从大到小排序
	//sort(list, list + 10, less<int>());			//从小到大排序
	
	for(int i = 0; i < 10 ; i++)
		cout << list[i] << endl;
	
	return 0;
}

2.2、自定义函数进行比较

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

bool cmp(const int &a, const int &b)
{
	return a > b;		//从大到小排序
}

int main()
{
	vector<int> list;
	
	for(int i = 0; i < 10 ; i++)
		list.push_back(rand());
	
	sort(list.begin(), list.end(), cmp);			
	
	for(int i = 0; i < 10 ; i++)
		cout << list[i] << endl;
	
	return 0;
}

2.3、用lambda函数进行比较

例子一,对vector进行排序。

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
	vector<int> list;
	
	for(int i = 0; i < 10 ; i++)
		list.push_back(rand());
	
	//从大到小排序
	sort(list.begin(), list.end(), [&](const int &a, const int &b){ return a > b; });			
	
	for(int i = 0; i < 10 ; i++)
		cout << list[i] << endl;
	
	return 0;
}

例子二,对vector<pair>进行排序。

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
	vector<pair<int, int>> list;
	
	for(int i = 0; i < 10 ; i++)
		list.push_back({i, rand()});
	
	//从大到小排序
	sort(list.begin(), list.end(), [&](const pair<int, int> &a, const pair<int, int> &b)
	{ return a.second > b.second; });			
	
	for(int i = 0; i < 10 ; i++)
		cout << list[i].first << endl;
	
	return 0;
}

2.4、结构体

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct Node
{
    int id, num;
    
    Node() {}
    Node(int x, int y) : id(x), num(y) {}

};

bool cmp(const Node &a, const Node &b)
{
    return a.num > b.num ;		//从大到小排序
}

int main()
{
	vector<Node> list;
	
	for(int i = 0; i < 10 ; i++)
		list.push_back(Node(i, rand()));
	
	//从大到小排序
	sort(list.begin(), list.end(), cmp);			
	
	for(int i = 0; i < 10 ; i++)
		cout << list[i].id << endl;

	return 0;
}
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__TAT__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值