如何创建一个按升序存储对的优先级队列?

How can I create a priority queue that stores pairs in ascending order?

我需要创建一个队列,按整数对的第一个值按升序存储它们。

假设我有以下队列:

0 10
0 10 
1 10 
2 10 
30 10

如果我尝试使用这些值创建一个优先级队列,它将按降序存储这些对,从 30 一直到 0。

有没有办法对队列进行排序或只在声明中设置顺序?

我正在尝试做:

priority_queue<pair<int, int>> queue;

for(int i=0; i<n; i++){
    cin>>t>>d;
    queue.push(make_pair(t, d));
}

对于priority_queue,最大的元素在队列的前面。

Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. That is, the front of the queue contains the "last" element according to the weak ordering imposed by Compare.

您可以使用 std::greater<pair<int,int>> 作为自定义比较器或您自己的比较器来进行自定义排序。这会将最小的元素放在队列的前面。

priority_queue<pair<int, int>, std::vector<pair<int,int>>, std::greater<pair<int,int>>> q;