#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();
}node
}ios
基本操做:函数
empty() 若是队列为空返回真spa
pop() 删除对顶元素队列
push() 加入一个元素ci
size() 返回优先队列中拥有的元素个数string
top() 返回优先队列对顶元素it
在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。io
使用方法:编译
头文件:
#include <queue>
声明方式:
一、普通方法:
priority_queue<int>q;
//经过操做,按照元素从大到小的顺序出队
二、自定义优先级:
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;//定义方法
//其中,第二个参数为容器类型。第三个参数为比较函数。
三、结构体声明方式:
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>
声明方法:
一、普通声明
queue<int>q;
二、结构体
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; }