优先队列排序规则重定义
  • 板块灌水区
  • 楼主Aa1424
  • 当前回复2
  • 已保存回复2
  • 发布时间2025/1/1 16:47
  • 上次更新2025/1/1 21:21:18
查看原帖
优先队列排序规则重定义
938357
Aa1424楼主2025/1/1 16:47
#include <iostream>
#include <queue>
#include <string>
using namespace std;

struct package
{
    int id;
    string data; 
    /*
	bool operator < (const package&b) const {
		return id<b.id;
	}
	*/
};

//自定义排序规则
//方法1 

bool operator<(package a, package b) {//如果是less(从小到大),重载小于号
    return a.id > b.id;//使用小于号使得大的先出队列	,反之是小的先出队 ,可以理解为优先级最高的在最右边 
}  
  
/*
bool operator>(package a, package b) {//如果是greater(从大到小),重载大于号
    return a.id > b.id;//使用小于号使得大的先出队列	,反之是小的先出队 ,可以理解为优先级最高的在最右边 
} 
*/

//方法2 
struct cmp1
{
	bool operator () (const package &a, const package &b)		  
	{
		return a.id < b.id;		
	}
};

int main() {
    priority_queue<package> tmp;//对应方法1,只能对应less,可以隐式的表达 
    //priority_queue<package,vector<package>,greater<package> > tmp;//对应方法1,若是greater,必须显示的表达 
    
	//priority_queue<package,vector<package>,cmp1> tmp;//对应方法2 
    tmp.push({2,"a"});
    tmp.push({3,"b"});
    tmp.push({14,"c"});
    tmp.push({-3,"g"});
    
    int size = tmp.size();
    while(size--) {
        cout << tmp.top().id << " " << tmp.top().data <<endl;
        tmp.pop();
    }
}
2025/1/1 16:47
加载中...