C++ usage of priority queue

#include <queue>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;

struct myps{
    int index;
    int val;
    myps(int x = 1, int y = 2):index(x), val(y){}
    
    // less 最大堆需要 
	friend bool operator < (const myps& px, const myps& py){
    	return px.val < py.val;
	}
	
	// greater 最小堆需要 
	friend bool operator > (const myps& px, const myps& py){
    	return px.val > py.val;
	}
};



int main(){
	myps *p = new myps[10]; 
	priority_queue<myps, vector<myps>, greater<myps> > pri;  // greater最小堆, less最大堆
	for(int i=0;i<10;i++){
		p[i].index = i;
		p[i].val = i+4;
		pri.push(p[i]);
	}
	
	while(!pri.empty()){
		myps p = pri.top();
		pri.pop();
		cout << p.index << " " << p.val << endl;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章