priority_queue 調用 STL里面的 make_heap(), pop_heap(), push_heap() 算法
實現,也算是堆的另外一種形式。
先寫一個用 STL 里面堆算法實現的與真正的STL里面的 priority_queue 用法相
似的 priority_queue, 以加深對 priority_queue 的理解


#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

class priority_queue


{
private:
vector<int> data;
public:

void push( int t )
{
data.push_back(t);
push_heap( data.begin(), data.end());
}

void pop()
{
pop_heap( data.begin(), data.end() );
data.pop_back();
}

int top()
{ return data.front(); }

int size()
{ return data.size(); }

bool empty()
{ return data.empty(); }
};


int main()


{
priority_queue test;
test.push( 3 );
test.push( 5 );
test.push( 2 );
test.push( 4 );

while( !test.empty() )
{
cout << test.top() << endl;
test.pop(); }
return 0;
}

STL里面的 priority_queue 寫法與此相似,只是增加了模板及相關的迭代器什么的。
priority_queue 對于基本類型的使用方法相對簡單。
他的模板聲明帶有三個參數,priority_queue<Type, Container, Functional>
Type 為數據類型, Container 為保存數據的容器,Functional 為元素比較方式。
Container 必須是用數組實現的容器,比如 vector, deque 但不能用 list.
STL里面默認用的是 vector. 比較方式默認用 operator< , 所以如果你把后面倆個
參數缺省的話,優先隊列就是大頂堆,隊頭元素最大。
看例子


#include <iostream>
#include <queue>

using namespace std;


int main()
{
priority_queue<int> q;
for( int i= 0; i< 10; ++i ) q.push( rand() );

while( !q.empty() )
{
cout << q.top() << endl;
q.pop();
}
getchar();
return 0;
}
如果要用到小頂堆,則一般要把模板的三個參數都帶進去。
STL里面定義了一個仿函數 greater<>,對于基本類型可以用這個仿函數聲明小頂堆
例子:


#include <iostream>
#include <queue>

using namespace std;


int main()
{
priority_queue<int, vector<int>, greater<int> > q;
for( int i= 0; i< 10; ++i ) q.push( rand() );

while( !q.empty() )
{
cout << q.top() << endl;
q.pop();
}
getchar();
return 0;
}
對于自定義類型,則必須自己重載 operator< 或者自己寫仿函數
先看看例子:


#include <iostream>
#include <queue>

using namespace std;


struct Node
{
int x, y;
Node( int a= 0, int b= 0 ):

x(a), y(b)
{}
};


bool operator<( Node a, Node b )
{
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}


int main()
{
priority_queue<Node> q;
for( int i= 0; i< 10; ++i )
q.push( Node( rand(), rand() ) );

while( !q.empty() )
{
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}
getchar();
return 0;
}
自定義類型重載 operator< 后,聲明對象時就可以只帶一個模板參數。
但此時不能像基本類型這樣聲明
priority_queue<Node, vector<Node>, greater<Node> >;
原因是 greater<Node> 沒有定義,如果想用這種方法定義
則可以按如下方式
例子:


#include <iostream>
#include <queue>

using namespace std;


struct Node
{
int x, y;
Node( int a= 0, int b= 0 ):

x(a), y(b)
{}
};


struct cmp
{

bool operator() ( Node a, Node b )
{
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x; }
};


int main()
{
priority_queue<Node, vector<Node>, cmp> q;
for( int i= 0; i< 10; ++i )
q.push( Node( rand(), rand() ) );

while( !q.empty() )
{
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}
getchar();
return 0;
}


posted on 2009-06-09 18:00
Darren 閱讀(15772)
評論(7) 編輯 收藏 引用