c++中priority_queue的用法


#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int main()
{
priority_queue<int> pq;//最大值優先隊列
priority_queue<int,deque<int>,greater<int> > pq2;//最小值優先隊列
pq.push(10);
pq.push(-1);
cout<<pq.top()<<endl;
cout<<pq.size()<<endl;
while(!pq.empty())
{
cout<< pq.top() <<endl;//每次刪除最大的
pq.pop();
}
pq2.push(100);
pq2.push(90);
while(!pq2.empty())
{
cout<< pq2.top() <<endl;//每次刪除最大的
pq2.pop();
}

}

基本操作:

empty() 如果隊列為空返回真

pop() 刪除對頂元素

push() 加入一個元素

size() 返回優先隊列中擁有的元素個數

top() 返回優先隊列對頂元素

在默認的優先隊列中,優先級高的先出隊。在默認的int型中先出隊的為較大的數。

使用方法:

頭文件:

#include <queue>

聲明方式:

1、普通方法:

priority_queue<int>q;
//通過操作,按照元素從大到小的順序出隊

 

2、自定義優先級:

struct cmp
{
operatorbool ()(int x, int y)
{
return x > y; // x小的優先級高
//也可以寫成其他方式,如: return p[x] > p[y];表示p[i]小的優先級高
}
};
priority_queue<int, vector<int>, cmp>q;//定義方法
//其中,第二個參數為容器類型。第三個參數為比較函數。

3、結構體聲明方式:

struct node
{
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() 返回隊列的長度

使用方法:

頭文件:

#include <queue>


聲明方法:

1、普通聲明

queue<int>q;


2、結構體

struct node
{
int x, y;
};
queue<node>q;



STL 中棧的使用方法(stack)

基本操作:

push(x) 將x加入棧中,即入棧操作

pop() 出棧操作(刪除棧頂),只是出棧,沒有返回值

top() 返回第一個元素(棧頂元素)

size() 返回棧中的元素個數

empty() 當棧為空時,返回 true


使用方法:

和隊列差不多,其中頭文件為:

#include <stack>


定義方法為:

stack<int>s1;//入棧元素為 int 型
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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM