C++ STL--stack/queue 的使用方法:
1、stack
stack 模板类的定义在<stack>头文件中。
stack 模板类需要两个模板参数,一个是元素类型,一个容器类型,但只有元素类型是必要
的,在不指定容器类型时,默认的容器类型为deque。
定义stack 对象的示例代码如下:
stack<int> s1;
stack<string> s2;
stack 的基本操作有:
入栈,如例:s.push(x);
出栈,如例:s.pop();注意,出栈操作只是删除栈顶元素,并不返回该元素。
访问栈顶,如例:s.top()
判断栈空,如例:s.empty(),当栈空时,返回true。
访问栈中的元素个数,如例:s.size()。
2、queue
queue 模板类的定义在<queue>头文件中。
与stack 模板类很相似,queue 模板类也需要两个模板参数,一个是元素类型,一个容器类
型,元素类型是必要的,容器类型是可选的,默认为deque 类型。
定义queue 对象的示例代码如下:
queue<int> q1;
queue<double> q2;
queue 的基本操作有:
入队,如例:q.push(x); 将x 接到队列的末端。
出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
访问队首元素,如例:q.front(),即最早被压入队列的元素。
访问队尾元素,如例:q.back(),即最后被压入队列的元素。
判断队列空,如例:q.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:q.size()。
#include <cstdlib> #include <iostream> #include <queue> #include<cstdio> using namespace std; int main() { int e,n,m; queue<int> q1; printf("push进去的:"); for(int i=0;i<10;i++) { q1.push(i); cout<<i<<" "; } cout<<endl; if(!q1.empty()) cout<<"队列不为空\n"; n=q1.size(); cout<<n<<endl; m=q1.back(); cout<<m<<endl; printf("pop出来的:"); for(int j=0;j<n;j++) { e=q1.front(); cout<<e<<" "; q1.pop(); } cout<<endl; if(q1.empty()) cout<<"队列为空\n"; return 0; }
#include <iostream> #include <queue> using namespace std; class T { public: int x, y, z; T(int a, int b, int c):x(a), y(b), z(c) { } }; bool operator < (const T &t1, const T &t2) { return t1.z < t2.z; // 按照z 的顺序来决定t1 和t2 的顺序 } main() { priority_queue<T> q; q.push(T(4,4,3)); q.push(T(2,2,5)); q.push(T(1,5,4)); q.push(T(3,3,6)); while (!q.empty()) { T t = q.top(); q.pop(); cout << t.x << " " << t.y << " " << t.z << endl; } return 1; }
再看一个按照z 的顺序从小到大出队的例子:
#include <iostream> #include <queue> using namespace std; class T { public: int x, y, z; T(int a, int b, int c):x(a), y(b), z(c) { } }; bool operator > (const T &t1, const T &t2) { return t1.z > t2.z; } main() { priority_queue<T, vector<T>, greater<T> > q; q.push(T(4,4,3)); q.push(T(2,2,5)); q.push(T(1,5,4)); q.push(T(3,3,6)); while (!q.empty()) { T t = q.top(); q.pop(); cout << t.x << " " << t.y << " " << t.z << endl; } return 1; } /*输出结果为: 4 4 3 1 5 4 2 2 5 3 3 6*/
如果我们把第一个例子中的比较运算符重载为: bool operator < (const T &t1, const T &t2) { return t1.z > t2.z; // 按照z 的顺序来决定t1 和t2 的顺序 } 则第一个例子的程序会得到和第二个例子的程序相同的输出结果。