结构体排序 重载 利用sort和优先队列的时候的“>“的区别

优先队列

优先队列里面默认是从大到小排序,这里的>符号将排序改成从小到大排序

#include<bits/stdc++.h>

using namespace std;
struct node
{
	int age;
	string name;
	bool operator < (const node &t) const
	{
		//将堆里面的内容按照,年龄从小到大排序 
		return age>t.age;
	}
}p[100];
int main()
{
	int n;
	cin>>n;
	priority_queue<node> heap;
	for(int i=0; i<n; i++) 
	{
		cin>>p[i].age>>p[i].name;
		heap.push({p[i].age,p[i].name});
	}
	for(int i=0; i<n; i++) 
	{
		node tmp = heap.top();
		heap.pop();
		cout<<tmp.age<<" "<<tmp.name<<endl;
	}
	return 0;
}
//4
//10 jack
//3 tom
//2 ak
//99 ac

在这里插入图片描述

sort

sort默认是从小到大排序 ,这里的">",让sort从大到小排序

#include<bits/stdc++.h>

using namespace std;
struct node
{
	int age;
	string name;
	bool operator < (const node &t) const
	{
		//利用sort,按照年龄小到大排序 
		return age>t.age;
	}
}p[100];
int main()
{
	int n;
	cin>>n;
	priority_queue<node> heap;
	for(int i=0; i<n; i++) 
	{
		cin>>p[i].age>>p[i].name;
		//heap.push({p[i].age,p[i].name});
	}
	sort(p,p+n);
	for(int i=0; i<n; i++) 
	{
//		node tmp = heap.top();
//		heap.pop();
		cout<<p[i].age<<" "<<p[i].name<<endl;
	}
	return 0;
}
//4
//10 jack
//3 tom
//2 ak
//99 ac

在这里插入图片描述

posted @ 2022-08-28 08:44  翔村亲亲鸟  阅读(44)  评论(0编辑  收藏  举报