如何创建优先队列以升序存储对?

发布于 2025-01-20 08:40:48 字数 372 浏览 2 评论 0原文

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

假设我有以下队列:

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

I need to create a queue that stores pairs of integers in ascending order by their first value.

Say I have the following queue:

0 10
0 10 
1 10 
2 10 
30 10

If I try to create a priority queue with these values, it's just going to store the pairs by descending order, starting with 30 all the way to 0.

Is there a way to sort the queue or to just set the order in the declaration?

I'm trying to do:

priority_queue<pair<int, int>> queue;

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸢与 2025-01-27 08:40:48

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

请注意,比较参数是定义的,以便如果其第一个参数以弱排序之前的第二个参数为之前,则其返回为true。但是,由于优先级队列首先输出最大的元素,因此“之前”的元素实际上是输出的。也就是说,队列的前部根据比较施加的弱排序包含“最后”元素。

您可以将std ::更大的&lt; pair&lt; int,int&gt;&gt;用作自定义比较器或您自己的比较器,也可以使用自定义订购。这将使最小的元素放在队列的前面。

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

For priority_queue, the largest element is at the front of the 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.

You could use std::greater<pair<int,int>> as custom comparator or your own comparator as well to have a custom ordering. This will put the smallest element at the front of the queue.

priority_queue<pair<int, int>, std::vector<pair<int,int>>, std::greater<pair<int,int>>> q;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文