c++ - 使用 std::greater

标签 c++ priority-queue

我很好奇 std::greater 的用途. 与 sort 一起使用时,它按降序输出数字。但是当与 priority_queue 一起使用时, 数字按升序输出。为什么会这样?

例子:

#include <iostream>     // std::cout
#include <functional>   // std::greater
#include <algorithm>    // std::sort
#include <queue>        // std::priority_queue

int main () {
  int numbers[]={20,40,50,10,30};
  std::priority_queue<int, std::vector<int>, std::greater<int>> pq (numbers, numbers+5);
  std::sort(numbers, numbers + 5, std::greater<int>());
  while(!pq.empty()){
      std:: cout << pq.top() << ' ';
      pq.pop();
  }
  std::cout << '\n';  
  for (int i=0; i<5; i++)
    std::cout << numbers[i] << ' ';
  return 0;
}

以上代码的输出是:

10 20 30 40 50 50 40 30 20 10

或者类似的行,

std::priority_queue<int, std::vector<int>, std::greater<int> >创建一个最小堆,而 std::priority_queue<int, std::vector<int>, std::less<int> >创建最大堆。本来可以反过来。为什么会这样?

最佳答案

引用 std::priority_queue at cppreference [强调我的]

A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.

A user-provided Compare can be supplied to change the ordering, e.g. using std::greater<T> would cause the smallest element to appear as the top().

所以这个顺序是预料之中的,与 std::sort 的方式没有真正的关系根据提供的二进制比较函数对元素进行排序。

Sorts the elements in the range [first, last) in ascending order.

...

Parameters

  • first, last - the range of elements to sort

  • policy - the execution policy to use. See execution policy for details.

  • comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.

作为std::greater将返回 true如果它的第一个参数大于它的第二个参数,我们希望元素在使用 std::sort 时按降序排序。与 std::greater作为执行比较的函数对象。


std::greater 恰好是用于在示例的这两个不同上下文中执行比较的函数对象。

关于c++ - 使用 std::greater,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52207107/

相关文章:

java - 将 PriorityQueue 转换为排序数组的最佳方法

c++ - 编译器是否优化了对虚方法的非多态调用?

c++ - 如何在 C++ 中 epur std::string?

c++ - 在 C++ 程序中使用 unicode

android - 使用 libzip 在 zip 中写入文件

java - 如何触发 PriorityQueue 的堆化?

c++ - 如何复制列表 vector ?

java - Prim算法优先级队列

dart - 如何实现Dart优先级队列(降序排列)

java - 并发处理严格顺序的消息