栈,队列与优先队列
STL提供3種特殊的數(shù)據(jù)結(jié)構(gòu):棧,隊(duì)列與優(yōu)先隊(duì)列
1.棧:符合“后進(jìn)后出”,有push和pop兩種操作
其中push把元素壓入棧頂,而pop從棧頂把元素“彈出”。頭文件<stack>
聲明棧:stack<int>s;
#include<iostream> #include<stack> #include<set> #include<vector> #include<map> using namespace std; typedef set<int> myset; map<myset,int> IDcache;//把集合映射成ID vector<myset> Setcache;//根據(jù)ID取集合 //查找集合的ID,如果找不到分配一個(gè)新ID int ID(myset x) {if(IDcache.count(x))return IDcache[x];Setcache.push_back(x);return IDcache[x]=Setcache.size()-1;} #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) int main() {stack<int> s;int n;cin>>n;for(int i=0;i<n;i++){string op;cin>>op;if(op[0]=='p') //push操作 s.push(ID(myset()));else if(op[0]=='D')s.push(s.top());else{myset x1=Setcache[s.top()];s.pop();myset x2=Setcache[s.top()];s.pop();myset x;if(op[0]=='U')set_union(ALL(x1),ALL(x2),INS(x));if(op[0]=='I')set_intersection(ALL(x1),ALL(x2),INS(x));if(op[0]=='A'){x=x2;x.insert(ID(x1));}s.push(ID(x));}cout<<Setcacher[s.top()].size()<<endl;} } View Code?
2.優(yōu)先隊(duì)列:是一種抽象數(shù)據(jù)類型,行為有些像隊(duì)列,但先進(jìn)隊(duì)列的元素不是先進(jìn)隊(duì)列的元素,而是隊(duì)列中優(yōu)先級(jí)最高的元素,這樣就可以允許類似于“急診病人插隊(duì)”這樣的事件發(fā)生。
頭文件:#include<queue>
聲明優(yōu)先隊(duì)列:priority_queue<int>pq;
出隊(duì)列的方式:由于出隊(duì)元素并不是最先進(jìn)隊(duì)的元素,出隊(duì)的方法由queue的front()變成了top().
在一些特殊情況下,需要使用自定義方式定義比較優(yōu)先級(jí)。? ?
只要元素定義了“小于”運(yùn)算符,就可以使用優(yōu)先隊(duì)列。
對(duì)于一些常見(jiàn)的優(yōu)先隊(duì)列,STL提供了
例如:要實(shí)現(xiàn)一個(gè)“個(gè)位數(shù)大的整數(shù)優(yōu)先級(jí)反而小”的優(yōu)先隊(duì)列。
可以定義一個(gè)結(jié)構(gòu)體cmp,重載“()”運(yùn)算符,使其“看上去”想一個(gè)函數(shù)(在c++中,重載了“()”運(yùn)算符的類或結(jié)構(gòu)體叫做仿函數(shù)),然后用“priority_queue<int,vector<int>,cmp> pq”的方式定義
struct cmp{
bool operator() (const int a,const int b) const{
return a%10>b%10;
}
};
?
轉(zhuǎn)載于:https://www.cnblogs.com/Aiahtwo/p/10358104.html
總結(jié)
- 上一篇: JavaWeb-SpringBoot(抖
- 下一篇: 質問力 C