STL提供3种特殊的数据结构:栈,队列与优先队列
1.栈:符合“后进后出”,有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;//根据ID取集合 //查找集合的ID,如果找不到分配一个新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; } }
2.优先队列:是一种抽象数据类型,行为有些像队列,但先进队列的元素不是先进队列的元素,而是队列中优先级最高的元素,这样就可以允许类似于“急诊病人插队”这样的事件发生。
头文件:#include<queue>
声明优先队列:priority_queue<int>pq;
出队列的方式:由于出队元素并不是最先进队的元素,出队的方法由queue的front()变成了top().
在一些特殊情况下,需要使用自定义方式定义比较优先级。
只要元素定义了“小于”运算符,就可以使用优先队列。
对于一些常见的优先队列,STL提供了
例如:要实现一个“个位数大的整数优先级反而小”的优先队列。
可以定义一个结构体cmp,重载“()”运算符,使其“看上去”想一个函数(在c++中,重载了“()”运算符的类或结构体叫做仿函数),然后用“priority_queue<int,vector<int>,cmp> pq”的方式定义
struct cmp{
bool operator() (const int a,const int b) const{
return a%10>b%10;
}
};