1

I am wondering why the default comparator "std::less" for the priority_queue() doesn't put the smallest element on the top? Instead, we need to supply the "std::greater" comparator in order to make the smallest element on the top. see example: http://neutrofoton.github.io/blog/2016/12/29/c-plus-plus-priority-queue-with-comparator/

Isn't this counter intuitive?

Thanks!

//helper function displays sorted data
template<class T>
void printQueue(T& q)
{
    while (!q.empty())
    {
        cout << q.top() << endl;
        q.pop();
    }
}

void SamplePriorityQueue()
{
    std::priority_queue<int, std::vector<int>, std::greater<int> > q;

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q.push(n);

    printQueue(q);
}

The output is:

1,
2,
3,
4
:
Edamame
  • 17,408
  • 44
  • 143
  • 254

0 Answers0