1. 程式人生 > >c++佇列 優先佇列的使用方法

c++佇列 優先佇列的使用方法

C++ Queues(佇列)

C++佇列是一種容器介面卡,它給予程式設計師一種先進先出(FIFO)的資料結構。
1.back() 返回一個引用,指向最後一個元素
2.empty() 如果佇列空則返回真
3.front() 返回第一個元素
4.pop() 刪除第一個元素
5.push() 在末尾加入一個元素
6.size() 返回佇列中元素的個數

佇列可以用線性表(list)或雙向佇列(deque)來實現(注意vector container 不能用來實現queue,因為vector 沒有成員函式pop_front!):
queue<list<int>> q1;
queue<deque<int>> q2;

其成員函式有“判空(empty)” 、“尺寸(Size)” 、“首元(front)” 、“尾元(backt)” 、“加入佇列(push)” 、“彈出佇列(pop)”等操作。

例:
1 int main()
2 {
3     queue<int> q;
4     q.push(4);
5     q.push(5);
6     printf("%d\n",q.front());
7     q.pop();
8 } /*
C++中優先佇列(priority queue<>)使用標頭檔案queue,需要宣告using namespace std;
常用來代替堆,每次直接加入新數即可,自動維護大小順序,使用很方便。
以大根堆為例,q.top( )是隊中最大的數。常用操作還有:q.push_back(x),q.pop( ) …
上面的程式是基本的建立佇列,可以建立大根堆或小根堆,不必強制記憶,每次除錯一下就可以了。
*/
/*


C++ Priority Queues(優先佇列)


C++優先佇列類似佇列,但是在這個資料結構中的元素按照一定的斷言排列有序。
1.empty() 如果優先佇列為空,則返回真
2.pop() 刪除第一個元素
3.push() 加入一個元素
4.size() 返回優先佇列中擁有的元素的個數
5.top() 返回優先佇列中有最高優先順序的元素


優先順序佇列可以用向量(vector)或雙向佇列(deque)來實現(注意list container 不能用來實現queue,因為list 的迭代器不是任意


存取iterator,而pop 中用到堆排序時是要求randomaccess iterator 的!):
priority_queue<vector<int>, less<int>> pq1; // 使用遞增less<int>函式物件排序
priority_queue<deque<int>, greater<int>> pq2; // 使用遞減greater<int>函式物件排序
其成員函式有“判空(empty)” 、“尺寸(Size)” 、“棧頂元素(top)” 、“壓棧(push)” 、“彈棧(pop)”等。
*/
#include<iostream>
#include<functional>
#include<queue>
using namespace std;
struct node
{
    friend bool operator< (node n1, node n2)
    {
        return n1.priority < n2.priority;  //"<"為從大到小排列,">"為從小到大排列
    }
    int priority;
    int value;
};
int main()
{
    const int len = 5;  //也可以寫在函式內
    int i;
    int a[len] = {3,5,9,6,2};
    //示例1
    priority_queue<int> qi;  //普通的優先順序佇列,按從大到小排序
    for(i = 0; i < len; i++)
        qi.push(a[i]);
    for(i = 0; i < len; i++)
    {
        cout<<qi.top()<<" ";
        qi.pop();
    }
    cout<<endl;
    //示例2
    priority_queue<int, vector<int>, greater<int> > qi2;  //從小到大的優先順序佇列,可將greater改為less,即為從大到小
    for(i = 0; i < len; i++)
        qi2.push(a[i]);
    for(i = 0; i < len; i++)
    {
        cout<<qi2.top()<<" ";
        qi2.pop();
    }
    cout<<endl;
    //示例3
    priority_queue<node> qn;  //必須要過載運算子
    node b[len];
    b[0].priority = 6; b[0].value = 1;
    b[1].priority = 9; b[1].value = 5;
    b[2].priority = 2; b[2].value = 3;
    b[3].priority = 8; b[3].value = 2;
    b[4].priority = 1; b[4].value = 4;
 
    for(i = 0; i < len; i++)
        qn.push(b[i]);
    cout<<"優先順序"<<'\t'<<"值"<<endl;
    for(i = 0; i < len; i++)
    {
        cout<<qn.top().priority<<'\t'<<qn.top().value<<endl;
        qn.pop();
    }
    return 0;
}