STL 中優先隊列的使用方法(priority_queu)
基本操作:
empty() 如果隊列爲空返回真
pop() 刪除對頂元素
push() 加入一個元素
size() 返回優先隊列中擁有的元素個數
top() 返回優先隊列對頂元素
在默認的優先隊列中,優先級高的先出隊。在默認的int型中先出隊的爲較大的數。
使用方法:
頭文件:
聲明方式:
1、普通方法:
//通過操作,按照元素從大到小的順序出隊
2、自定義優先級:
{
operatorbool ()(int x, int y)
{
return x > y; // x小的優先級高
//也可以寫成其他方式,如: return p[x] > p[y];表示p[i]小的優先級高
}
};
priority_queue<int, vector<int>, cmp>q;//定義方法
//其中,第二個參數爲容器類型。第三個參數爲比較函數。
3、結構體聲明方式:
{
int x, y;
friend booloperator< (node a, node b)
{
return a.x > b.x; //結構體中,x小的優先級高
}
};
priority_queue<node>q;//定義方法
//在該結構中,y爲值, x爲優先級。
//通過自定義operator<操作符來比較元素中的優先級。
//在重載”<”時,最好不要重載”>”,可能會發生編譯錯誤
STL 中隊列的使用(queue)
基本操作:
push(x) 將x壓入隊列的末端
pop() 彈出隊列的第一個元素(隊頂元素),注意此函數並不返回任何值
front() 返回第一個元素(隊頂元素)
back() 返回最後被壓入的元素(隊尾元素)
empty() 當隊列爲空時,返回true
size() 返回隊列的長度
使用方法:
頭文件:
聲明方法:
1、普通聲明
2、結構體
{
int x, y;
};
queue<node>q;
STL 中棧的使用方法(stack)
基本操作:
push(x) 將x加入棧中,即入棧操作
pop() 出棧操作(刪除棧頂),只是出棧,沒有返回值
top() 返回第一個元素(棧頂元素)
size() 返回棧中的元素個數
empty() 當棧爲空時,返回 true
使用方法:
和隊列差不多,其中頭文件爲:
定義方法爲:
stack<string>s2;// 入隊元素爲string型
stack<node>s3;//入隊元素爲自定義型
/**//*
*===================================*
| |
| STL中優先隊列使用方法 |
| |
| chenlie |
| |
| 2010-3-24 |
| |
*===================================*
*/
#include <iostream>
#include <vector>
#include <queue>
usingnamespace std;
int c[100];
struct cmp1
{
booloperator ()(int x, int y)
{
return x > y;//小的優先級高
}
};
struct cmp2
{
booloperator ()(constint x, constint y)
{
return c[x] > c[y];
// c[x]小的優先級高,由於可以在對外改變隊內的值,
//所以使用此方法達不到真正的優先。建議用結構體類型。
}
};
struct node
{
int x, y;
friend booloperator< (node a, node b)
{
return a.x > b.x;//結構體中,x小的優先級高
}
};
priority_queue<int>q1;
priority_queue<int, vector<int>, cmp1>q2;
priority_queue<int, vector<int>, cmp2>q3;
priority_queue<node>q4;
queue<int>qq1;
queue<node>qq2;
int main()
{
int i, j, k, m, n;
int x, y;
node a;
while (cin >> n)
{
for (i =0; i < n; i++)
{
cin >> a.y >> a.x;
q4.push(a);
}
cout << endl;
while (!q4.empty())
{
cout << q4.top().y <<""<< q4.top().x << endl;
q4.pop();
}
// cout << endl;
}
return0;
}