1. 程式人生 > >優先順序佇列priority_queue之比較函式

優先順序佇列priority_queue之比較函式

STL預設的比較函式



greater是升序排列,後面的大於前面的

less是降序排列,後面的小於前面的

在初始化優先順序佇列時預設是less

priority_queue<int,vector<int>,less<int> > que與priority_queue<int > que是一樣的效果

也可以自己寫比較函式

struct cmp{
    bool operator() ( int a , int b ){
return a< b;      //與greater是等價的
         }
};

priority_queue<int,vector<int>,cmp > p;

另外特別是在結構不是基本結構的比較時,最好自己寫比較函式,比較速度能夠提高不少

#include<iostream>
#include<string>
#include<queue>
#include<time.h>
#include<algorithm>
#include <functional>
using namespace std;

typedef pair<int,int>int2;

struct cmp{
    bool operator() ( int2 a, int2 b ){return a.first< b.first;}
};

int main()
{
	//priority_queue<int2,vector<int2>,greater<int2> > p1;
	priority_queue<int2,vector<int2>,cmp > p1;
	p1.push(int2(1,2));
	p1.push(int2(3,4));
	p1.push(int2(2,8));
	p1.push(int2(5,0));
	for(int i=0;i<4;i++)
	{
		int2 temp=p1.top();p1.pop();
		printf("(%d,%d)\n",temp.first,temp.second);
	}

	system("pause");
	return 0;

}