📜  C++中对的优先级队列(按先排序)

📅  最后修改于: 2021-10-28 02:11:27             🧑  作者: Mango

在 C++ 中,priority_queue 实现了堆。以下是创建对类型的优先级队列的一些示例。

按第一个元素排序的最大优先级队列(或最大堆)

// C++ program to create a priority queue of pairs.
// By default a max heap is created ordered
// by first element of pair.
#include 
  
using namespace std;
  
// Driver program to test methods of graph class
int main()
{
    // By default a max heap is created ordered
    // by first element of pair.
    priority_queue > pq;
  
    pq.push(make_pair(10, 200));
    pq.push(make_pair(20, 100));
    pq.push(make_pair(15, 400));
  
    pair top = pq.top();
    cout << top.first << " " << top.second;
    return 0;
}

输出 :

20 100


按第一个元素排序的最小优先级队列(或最小堆)

// C++ program to create a priority queue of pairs.
// We can create a min heap by passing adding two 
// parameters, vector and greater().
#include 
  
using namespace std;
  
typedef pair pi;
  
// Driver program to test methods of graph class
int main()
{
    // By default a min heap is created ordered
    // by first element of pair.
    priority_queue, greater > pq;
  
    pq.push(make_pair(10, 200));
    pq.push(make_pair(20, 100));
    pq.push(make_pair(15, 400));
  
    pair top = pq.top();
    cout << top.first << " " << top.second;
    return 0;
}

输出 :

10 200

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。