C++ Queues(隊列)

C++隊列是一種容器適配器,它給予程序員一種先進(jìn)先出(FIFO)的數(shù)據(jù)結(jié)構(gòu)。
1.back() 返回一個引用,指向最后一個元素
2.empty() 如果隊列空則返回真
3.front() 返回第一個元素
4.pop() 刪除第一個元素
5.push() 在末尾加入一個元素
6.size() 返回隊列中元素的個數(shù)

隊列可以用線性表(list)或雙向隊列(deque)來實現(xiàn)(注意vector container 不能用來實現(xiàn)queue,因為vector 沒有成員函數(shù)pop_front!):
queue<list<int>> q1;
queue<deque<int>> q2;
其成員函數(shù)有“判空(empty)” 、“尺寸(Size)” 、“首元(front)” 、“尾元(backt)” 、“加入隊列(push)” 、“彈出隊列(pop)”等操作。

例:

int main()
{
   queue<int> q;
   q.push(4);
   q.push(5);
   printf("%d\n",q.front());
   q.pop();
}


C++ Priority Queues(優(yōu)先隊列)

C++優(yōu)先隊列類似隊列,但是在這個數(shù)據(jù)結(jié)構(gòu)中的元素按照一定的斷言排列有序。
1.empty() 如果優(yōu)先隊列為空,則返回真
2.pop() 刪除第一個元素
3.push() 加入一個元素
4.size() 返回優(yōu)先隊列中擁有的元素的個數(shù)
5.top() 返回優(yōu)先隊列中有最高優(yōu)先級的元素

優(yōu)先級隊列可以用向量(vector)或雙向隊列(deque)來實現(xiàn)(注意list container 不能用來實現(xiàn)queue,因為list 的迭代器不是任意存取iterator,而pop 中用到堆排序時是要求randomaccess iterator 的!):
priority_queue<vector<int>, less<int>> pq1; // 使用遞增less<int>函數(shù)對象排序
priority_queue<deque<int>, greater<int>> pq2; // 使用遞減greater<int>函數(shù)對象排序
其成員函數(shù)有“判空(empty)” 、“尺寸(Size)” 、“棧頂元素(top)” 、“壓棧(push)” 、“彈棧(pop)”等。

例:

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


     輸出結(jié)果為(注意是按照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; 
}


     輸出結(jié)果為: 
     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的順序} 則第一個例子的程序會得到和第二個例子的程序相同的輸出結(jié)果。