STL 队列、优先队列、栈
queue和priority_queue的头文件都是#include<queue> stack的头文件是#include<stack>
queue<typename>q eg:queue<int>q 本身先进先出
q.push(x)压队尾,q.pop()队首元素出栈 q.empty()判断队列是否为空 q.size()返回里面元素的个数
q.front()访问队首元素 q.back()访问队尾
priority_queue<typename>pq eg:priority_queue<int>pq,优先队列按照里面的元素默认按照最大值在队首。(int之类的是数字大在前面,char是字典序)
优先队列也有pop,push,empty,size功能相同
默认的缺省定义和priority_queue<int,vector<int>,less<int> >是一样的,如果less<int>换成greater<int>这个变成最小值在前面(这三个的typename要统一)
有时候顺序需要自定义,或者是结构体之类的不容易比较的,这时候在struct里面使用友元函数重载小于号或者新建structcmp直接重载(),这两个return的和实际序列相反的哦(跟sort的cmp比较的)
比如return a<b,实际排序就是按照队首最大排序的 具体代码如下。 优先队列没有front和back,只有top
(friend和cmp出来的都是反的哦!)
#include<iostream> #include<queue> using namespace std; struct fruit { string name; int price; friend bool operator <(fruit f1,fruit f2) { return f1.price<f2.price; } }f1,f2,f3; int main() { priority_queue<fruit> q; f1.name="桃子"; f1.price=3; f2.name="梨子"; f2.price=4; f3.name="苹果"; f3.price=1; q.push(f1); q.push(f2); q.push(f3); cout<<q.top().name<<q.top().price<<endl; return 0; }
#include<queue> #include<iostream> using namespace std; struct fruit { string name; int price; }f1,f2,f3; struct cmp { bool operator () (fruit f1,fruit f2) { return f1.price<f2.price; } }; int main() { priority_queue<fruit,vector<fruit>,cmp>q; f1.name="桃子"; f1.price=3; f2.name="梨子"; f2.price=4; f3.name="苹果"; f3.price=1; q.push(f1); q.push(f2); q.push(f3); cout<<q.top().name<<q.top().price<<endl; return 0; }
如果遇到较大范围的需要比较的,在fruit a的位置变成const fruit &a,其余不变,cmp和小于号都适用
在使用front或者top的时候需要确保队列不为空,不然可能出现奇怪的结果。
栈是后进先出的
stack<typename>s
访问只能s.top()访问栈顶,还有s.pop(),s.push(x),s.empty(),s=.size()