我很好奇 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. usingstd::greater<T>
would cause the smallest element to appear as thetop()
.
所以这个顺序是预料之中的,与 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 returnstrue
if thefirst
argument is less than (i.e. is ordered before) thesecond
.
作为std::greater
将返回 true
如果它的第一个参数大于它的第二个参数,我们希望元素在使用 std::sort
时按降序排序。与 std::greater
作为执行比较的函数对象。
即 std::greater
恰好是用于在示例的这两个不同上下文中执行比较的函数对象。
关于c++ - 使用 std::greater,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52207107/