使用 std::greater

Use of std::greater

我很好奇 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 将 return true 如果它的第一个参数 大于 它的第二个参数,我们希望元素被排序当使用 std::sortstd::greater 作为执行比较的函数对象时按降序排列。


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