1. 程式人生 > >C++ STL--stack/queue 的使用方法

C++ STL--stack/queue 的使用方法

1、stack
stack 模板類的定義在標頭檔案中。
stack 模板類需要兩個模板引數,一個是元素型別,一個容器型別,但只有元素型別是必要
的,在不指定容器型別時,預設的容器型別為deque。
定義stack 物件的示例程式碼如下:
stack s1;
stack s2;
stack 的基本操作有:
入棧,如例:s.push(x);
出棧,如例:s.pop();注意,出棧操作只是刪除棧頂元素,並不返回該元素。
訪問棧頂,如例:s.top()
判斷棧空,如例:s.empty(),當棧空時,返回true。
訪問棧中的元素個數,如例:s.size()。

2、queue
queue 模板類的定義在標頭檔案中。
與stack 模板類很相似,queue 模板類也需要兩個模板引數,一個是元素型別,一個容器類
型,元素型別是必要的,容器型別是可選的,預設為deque 型別。
定義queue 物件的示例程式碼如下:
queue q1;
queue q2;

queue 的基本操作有:
入隊,如例:q.push(x); 將x 接到佇列的末端。
出隊,如例:q.pop(); 彈出佇列的第一個元素,注意,並不會返回被彈出元素的值。
訪問隊首元素,如例:q.front(),即最早被壓入佇列的元素。
訪問隊尾元素,如例:q.back(),即最後被壓入佇列的元素。
判斷佇列空,如例:q.empty(),當佇列空時,返回true。
訪問佇列中的元素個數,如例:q.size()

#include <cstdlib>
#include <iostream>
#include <queue>

using namespace
std; int main() { int e,n,m; queue<int> q1; for(int i=0;i<10;i++) q1.push(i); if(!q1.empty()) cout<<"dui lie bu kong\n"; n=q1.size(); cout<<n<<endl; m=q1.back(); cout<<m<<endl; for(int j=0;j<n;j++) { e=q1.front(); cout
<<e<<" "; q1.pop(); } cout<<endl; if(q1.empty()) cout<<"dui lie bu kong\n"; system("PAUSE"); return 0; }

3、priority_queue
在標頭檔案中,還定義了另一個非常有用的模板類priority_queue(優先佇列)。優先隊
列與佇列的差別在於優先佇列不是按照入隊的順序出隊,而是按照佇列中元素的優先權順序
出隊(預設為大者優先,也可以通過指定運算元來指定自己的優先順序)。
priority_queue 模板類有三個模板引數,第一個是元素型別,第二個容器型別,第三個是比
較運算元。其中後兩個都可以省略,預設容器為vector,預設運算元為less,即小的往前排,大
的往後排(出隊時序列尾的元素出隊)。
定義priority_queue 物件的示例程式碼如下:
priority_queue q1;
priority_queue< pair

#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 的順序從大到小出隊的):
3 3 6
2 2 5
1 5 4
4 4 3
再看一個按照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 的順序
}