Search code examples
c++c++11stlpriority-queue

Difference between compare order of std::sort and priority_queue (C++)


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?


Solution

  • 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