Search code examples
c++stdpriority-queuestd-pairmin-heap

std::greater on a an std::pair of a double and a class


Does std::greater work when you have a std::pair of int and a class?

I am trying to create a priority queue of pairs, ordered by the first element:

std::priority_queue<std::pair<double, classA>, std::vector<std::pair<double, classA>>, std::greater<std::pair<double, classA>>> priorityQueue

But I get an error that says

no match for 'operator<'`

And it alludes to the second element of the std::pair, which is of class type.

Is std::greater applied to the first and second elements of the std::pair?


Solution

  • std::greater is just a wrapper for a call to operator < of the template type. For std::pair we can check the reference site here and we see it says

    Compares lhs and rhs lexicographically by operator<, that is, compares the first elements and only if they are equivalent, compares the second elements.

    So, it uses the operator < of both types, which means your class type needs to supply it. Since it doesn't you get the compiler error.