std::greater 在 std::priority_queue 中的行为是什么?

What is the behavior of std::greater in std::priority_queue?

当我在std::sort中使用std::greater<int>作为比较函数对象时如下:

std::sort(array_name, array_name + length, std::greater<int>());

数组非递增排序(即最大的在前)

但是,当我在 std::priority_queue 中使用相同的比较函数时,如下所示:

std::priority_queue <int, std::vector<int>, std::greater<int> > pq_name;

为什么std::priority_queue::top成员函数returns先是最小的数?

(我需要对这两种情况进行清楚的比较)

CPPRef says on it:

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

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.

因此,对于基于 std::less 的默认排序,队列顶部是最大的元素,排序时排在最后的元素。 OTOH std::greater 最后一个元素是最小的。

为了理解为什么会发生这种情况,您必须了解您正在使用的数据结构。

问:什么是数组? A: 数组是包含类型的连续内存区域。就我们而言,它可以包含任何类型的对象。但是由于您使用的是 int,在 C++ 中,整数通常由 32 位组成,但这取决于具体情况。因此,您在内存中的表示类似于

| 4 bytes | 4 bytes | 4 bytes | (...)

当您对数组进行排序时,std::greater<int>运算符将"sort"您的数组,方法是将较大的整数放在第一个位置,第二大的值放在第二个位置,依此类推.

问:什么是std::priority_queueA: 优先级队列是一个堆,更具体地说,是一个二叉树。堆是一种数据结构,默认优化为 return 最大值。这种类型的堆称为 max heaps。但是,当您使用 std::greater 运算符在 priority_queue 中重载比较时,您正在将堆转换为 min 堆 。这种堆,类似于重载 std::sort 方法运算符时发生的情况,实现为首先检索最小值。

请记住,堆在内存中的表示与数组中的完全不同。