【问题标题】:Difference between compare order of std::sort and priority_queue (C++)std::sort 和 priority_queue (C++) 的比较顺序之间的区别
【发布时间】:2021-10-20 18:17:19
【问题描述】:

我想知道为什么priority_queuevector 的工作方式完全不同。这是示例:

priority_queue<int, vector<int>, less<int> > pq;
pq.push(1);
pq.push(2);
pq.push(3);
// if we print the elem in pq by pop(), we get 3, 2, 1
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
std::sort(v.begin(), v.end(), less<int>()); 
// but we get 1, 2, 3 for vector

priority_queuevector 都使用了less,但是为什么结果不一样呢?

【问题讨论】:

    标签: c++ c++11 stl priority-queue


    【解决方案1】:

    std::lesspriority_queue的默认compartor,std::vector是默认Container,所以你的代码可以简化为:

    priority_queue<int> pq;
    

    根据doc,预计通过pop获得最大值

    优先级队列是提供恒定时间的容器适配器 查找最大(默认)元素,代价是 对数插入和提取。

    实际上,我们得到一个max heapstd::less 作为比较器,这看起来不是很直观。要获得min heap,我们需要使用std::greater 作为比较器。

    Related question to see more underly details

    【讨论】:

    • 我的问题是,为什么它们的工作方式不同?使用相同的std::lesspriority_queue 给我降序,sort 给我升序(如我所料)。就像你说的,std::less 是默认值,但为什么它们会相反呢?仅仅是因为我们默认将“堆”视为“最大堆”吗?按照惯例?
    • @J.Victor 这是设计使然,虽然它不是很直观,但我们会得到一个max heap,其中 std::less 作为比较器
    • @J.Victor 有一个相关问题:stackoverflow.com/questions/25590546/…查看更多详情
    【解决方案2】:

    std::priority_queue 实现为堆,当你插入元素时它会自动排序。 less&lt;int&gt; 表示它是最大堆。当您使用pop() 弹出一个元素时,您将获得堆中最大的元素。 您可以从 cppreference 获得更详细的描述:

    Compare - 一种提供严格弱排序的比较类型。 请注意,Compare 参数被定义为如果它的第一个参数在弱排序中位于其第二个参数之前,则它返回 true。但是因为优先级队列首先输出最大的元素,所以“先来”的元素实际上是最后输出的。也就是说,根据比较强加的弱排序,队列的前面包含“最后一个”元素。

    priority_queue

    std::sort 最可能使用 QuickSort,less&lt;int&gt; 表示按升序对元素进行排序。

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 2012-05-08
      • 2017-07-28
      • 2018-02-28
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多