C++ 優先級隊列(priority_queue)用法


要使用priority_queue需要先包含頭文件#include<queue>,相比queue,優先隊列可以自定義數據的優先級,讓優先級高的排在隊列前面。

優先隊列的基本操作:

empty:查看優先隊列是否為空

size:返回優先隊列的長度

top:查看堆頂的元素

push:插入一個元素

emplace:構造一個元素並插入隊列

pop:移除堆頂的元素

swap:交換兩個優先隊列的內容

模板定義:

template <class T, class Container = vector<T>, 
class Compare = less<typename Container::value_type> > class priority_queue;

T是數據類型。

Container是存儲數據的容器類型,其存儲的數據類型必須是T。默認的容器是vector,也可以使用deque

Compare是進行比較的方法,對於comp(a,b)這種比較方法,如果a的排序是在b之前,那么應該返回true。對於默認的比較方法是less<T>,即返回的是 a<b。對於堆中任意一個節點node,它的父節點永遠比它大。故在默認情況下,priority_queue是大頂堆。

1.基本操作的使用:

#include <iostream>
#include <queue>
#include <vector>
#include <functional>

using namespace std;

int main()
{
    int num[] = {10, 30, 20, 90, 120, 50};
    priority_queue<int> pq1;
    priority_queue<int> pq2(num, num + 6);                            //默認情況大頂堆
    priority_queue<int, vector<int>, greater<int> > pq3(num, num + 6); //小頂堆

    cout << "pq1 is empty? " << (pq1.empty() ? "yes" : "no") << endl;
    cout << "the size of pq2 is " << pq2.size() << endl;

    cout << "the top of pq2 is " << pq2.top() << endl;
    cout << "the top of pq3 is " << pq3.top() << endl;

    pq1.push(30);
    cout << "the top of pq1 is " << pq1.top() << endl;
    pq1.emplace(10);

    pq1.pop();
    cout << "the top of pq1 is " << pq1.top() << endl;

    swap(pq1, pq2);
    cout << "the top of pq1 is " << pq1.top() << endl;
    cout << "the top of pq2 is " << pq2.top() << endl;
}

結果

pq1 is empty? yes
the size of pq2 is 6
the top of pq2 is 120
the top of pq3 is 10
the top of pq1 is 30
the top of pq1 is 30
the top of pq1 is 10
the top of pq1 is 120
the top of pq2 is 10

2.自定義對象的比較

#include <iostream>
#include <queue>
#include <vector>
#include <functional>

using namespace std;

class Node
{
public:
    int x, y;
    Node(int x, int y) : x(x), y(y) {}

    bool operator<(const Node &a) const		//方法1:重載運算符
    {
        return (x * x + y * y) < (a.x * a.x + a.y * a.y);
    }

    bool operator>(const Node &a) const
    {
        return (x * x + y * y) > (a.x * a.x + a.y * a.y);
    }
};

template <typename T>		//方法2:自定義比較方法,下面也是STL中greater<T>的實現方法
struct mycmp
{
    bool operator()(const T &a, const T &b) const
    {
        return a > b;
    }
};

int main()
{
    Node n1(1, 1);
    Node n2(3, 4);
    Node n3(2, 0);
    priority_queue<Node> pq1;	//大頂堆
    pq1.push(n1);
    pq1.push(n2);
    pq1.push(n3);
    while (!pq1.empty())
    {
        cout << pq1.top().x << "," << pq1.top().y << endl;
        pq1.pop();
    }
	cout<<endl;
    
    priority_queue<Node, vector<Node>, mycmp<Node> > pq2;	//小頂堆
    pq2.push(n1);
    pq2.push(n2);
    pq2.push(n3);
    while (!pq2.empty())
    {
        cout << pq2.top().x << "," << pq2.top().y << endl;
        pq2.pop();
    }
    return 0;
}

結果

3,4
2,0
1,1

1,1
2,0
3,4


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM