stack 、queue、priority_queue(stl)
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
stack<int>s;
void _stack(){
for(int i = 0 ; i <= 4; i++)
s.push(i);
cout <<s.top()<<endl;
s.emplace(233);//對于在容器中添加類的對象時, 相比于push_back,emplace_back可以避免額外類的復(fù)制和移動操作.
cout <<s.top()<<endl;
}
void _queue(){
queue<int>q;
q.push(1);
if(!q.empty()){
cout << q.front() <<endl;
q.pop();
}
}
void p_q(){
priority_queue<int> bigtosmall;
priority_queue<int,vector<int>,greater<int> >smalltobig;
for(int i = 1; i <= 10 ; i++){
bigtosmall.push(i);
smalltobig.push(i);
}
while(!bigtosmall.empty()){
cout << bigtosmall.top() <<" ";
bigtosmall.pop();
}
cout <<endl;
while(!smalltobig.empty()){
cout << smalltobig.top() <<" ";
smalltobig.pop();
}
cout <<endl;
}
int main(){
_stack();
_queue();
p_q();
}
單調(diào)棧
實現(xiàn)一個棧,除了push和pop操作,還要實現(xiàn)min函數(shù)以返回棧中的最小值。 push,pop和min函數(shù)的時間復(fù)雜度都為O(1)。
維護一個單調(diào)遞減的棧,所棧首就是當(dāng)前的最小值,pop的時候如果單調(diào)棧首的序號是這個,那也要pop這個單調(diào)棧,數(shù)值可能重復(fù),所以單調(diào)棧維護的是同一個值的最小序號。