-1

I am wondering why priority_queue and vector work the totally different way. Here is the sample:

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

Both priority_queue and vector used less, but why the result is different?

J. Victor
  • 27
  • 1
  • 4

2 Answers2

1

std::less is the default compartor for priority_queue, and std::vector is the default Container, so your code can be simplified as:

priority_queue<int> pq;

According to the doc, it's expected to get the largest value via pop

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.

Actually, we get a max heap with std::less as a comparator, this doesn't seem very intuitive. To get a min heap, we need to use std::greater as a comparator.

Related question to see more underly details

prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42
  • My question is, why do they work differently? With using the same ```std::less```, ```priority_queue``` gives me descending order, and ```sort``` gives me ascending order(as I expected). Like you said, ```std::less``` is the default, but why do they work the opposite? Is it just because we think a "heap" as "max heap" by default? Conventionally? – J. Victor Aug 19 '21 at 01:57
  • @J.Victor It's by design, though it's not very intuitive, we get a `max heap` with std::less as a comparator – prehistoricpenguin Aug 19 '21 at 02:04
  • @J.Victor There is a related question: https://stackoverflow.com/questions/25590546/why-does-stdpriority-queue-use-max-heap-instead-of-min-heap#:%7E:text=Priority_queue%20is%20adapted%20from%20make_heap,So%20it%20is%20max%20heap to see more details – prehistoricpenguin Aug 19 '21 at 02:34
1

The std::priority_queue implemented as a heap, it will automatically sort when you insert elements. less<int> means it is the max-heap. When you use pop() to pop an element, you will get the largest element in the heap. You can get a more detailed description from cppreference:

Compare - A Compare type providing a strict weak ordering. 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.

priority_queue

The std::sort is most likely to use QuickSort, less<int> means sorts the elements in ascending order.

Yachen
  • 11
  • 2