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

1、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>
  
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;
}

2、priority_queue
在<queue>頭文件中,還定義了另一個非常有用的模板類priority_queue(優先隊列)。優先隊
列與隊列的差別在於優先隊列不是按照入隊的順序出隊,而是按照隊列中元素的優先權順序
出隊(默認爲大者優先,也可以通過指定算子來指定自己的優先順序)。
priority_queue 模板類有三個模板參數,第一個是元素類型,第二個容器類型,第三個是比
較算子。其中後兩個都可以省略,默認容器爲vector,默認算子爲less,即小的往前排,大
的往後排(出隊時序列尾的元素出隊)。
定義priority_queue 對象的示例代碼如下:
priority_queue<int> q1;
priority_queue< pair<int, int> > q2; // 注意在兩個尖括號之間一定要留空格。
priority_queue<int, vector<int>, greater<int> > q3; // 定義小的先出隊
priority_queue 的基本操作與queue 相同。
初學者在使用priority_queue 時,最困難的可能就是如何定義比較算子了。
如果是基本數據類型,或已定義了比較運算符的類,可以直接用STL 的less 算子和greater
算子——默認爲使用less 算子,即小的往前排,大的先出隊。
如果要定義自己的比較算子,方法有多種,這裏介紹其中的一種:重載比較運算符。優先隊
列試圖將兩個元素x 和y 代入比較運算符(對less 算子,調用x<y,對greater 算子,調用x>y),
若結果爲真,則x 排在y 前面,y 將先於x 出隊,反之,則將y 排在x 前面,x 將先出隊。
看下面這個簡單的示例:

#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;
}

 

如果我們把第一個例子中的比較運算符重載爲:
bool operator < (const T &t1, const T &t2)
{
        return t1.z > t2.z; // 按照z 的順序來決定t1 和t2 的順序
}
則第一個例子的程序會得到和第二個例子的程序相同的輸出結果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章