sort 和优先队列的排序方法

1.sort 用内置头文件的排序方式来排序

#include<algorithm>
#include<functional>//内置排序方式的头文件

using namespace std;

sort(a,a+n,greater<int >())//降序来排列
sort(a,a+n,less<int> ()) //升序来排列

2结构体内部重载

#include<algorithm>
#include<vector>


struct node{
	int num;
	char name[20];
	friend bool operator <(node a ,node b){
		if(strcmp(a.name,b.name)==0)
			return a.num<b.num;
	}
};
vector <node> v; 
sort(v.begin(),v.end())
//优先队列就不用用sort了,因为放进去之后结构体内部重载就已经确定好优先级了

上面的也可以直接将数据存在结构体数组里面,不过也必须要用sort排个序。 

1优先队列普通情况

#include<iostream>
#include<queue>
#include<functional>

using namespace std;
//
//int main()
//{
//	priority_queue<int > q;//默认数越大优先级越大 
//}

2对于常见的优先队列,内置函数提供了一些简便方法“越小的整数优先级越大的优先队列”

priority_queue<int ,vector<int>,greater<int> >q 

其中第一个参数是元素的类型第二个参数是容器的类型,第三个是排序的方法默认为less<int >  是越大的整数优先级越大。
 

#include<iostream>
#include<queue>
#include<functional>

using namespace std;

struct cmp{//用int &a 是因为元素类型为int 
	bool operator ()(int &a,int &b){//(const int a,const int b)const {} 
		return a>b;//等同于greater<int > //最小值优先 
	}
};
int main()
{
	priority_queue<int ,vector<int>,greater<int> >q //前面不用定义vector也可以直接向优先队列里面加元素

//第三个参数的替换cmp 
	priority_queue<int ,vector<int>,cmp >q 
} 

3,结构体优先队列,需要在结构体内部重载‘<’,之前博客里面写过,有兴趣的话可以看一下

结构体优先队列传送门

在C++,我们可以通过自定义比较函数来实现自定义优先队列排序。比较函数是一个返回布尔值的函数,用于确定元素的优先级。在优先队列,元素按照默认的排序规则进行排序,即大根堆或小根堆。默认情况下,元素按照从大到小的顺序排列,也就是大根堆。如果要实现不同的排序规则,我们可以自定义比较函数来改变元素的排序顺序。 下面是一个示例代码,展示了如何在C++自定义优先队列排序: ```cpp #include <iostream> #include <queue> using namespace std; // 自定义比较函数,实现从小到大的排序规则 struct Compare { bool operator() (int a, int b) { return a > b; } }; void custom_priority_queue_sort() { int source_data = {3, 5, 8, 1, 10, 2, 9, 15, 13, 16}; priority_queue<int, vector<int>, Compare> q; // 使用自定义的比较函数 for (auto n : source_data) q.push(n); while (!q.empty()) { cout << q.top() << endl; q.pop(); } } int main() { custom_priority_queue_sort(); return 0; } ``` 在上述代码,我们定义了一个名为`Compare`的结构体,其重载了小括号运算符`()`。在自定义的比较函数,我们将元素按照从小到大的顺序排列,即返回`a > b`。然后在创建优先队列时,我们通过指定自定义比较函数`Compare`来改变排序规则。 运行以上代码,输出结果为: ``` 1 2 3 5 8 9 10 13 15 16 ``` 以上代码演示了如何在C++自定义优先队列排序规则。通过自定义比较函数,我们可以实现各种不同的排序方式来满足特定需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值