0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

2 Answers2

5

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Thank you for clarifying. Since I don't have anything to compare in my class, how do I define operator< ? – sometimesLazy Jun 17 '20 at 17:11
  • @sometimesLazy I wouldn't. What I would do is write a custom comparator that only looks at the `double` part of the pair. For how, see: https://stackoverflow.com/questions/16111337/declaring-a-priority-queue-in-c-with-a-custom-comparator – NathanOliver Jun 17 '20 at 17:21
  • Thank you for this! :) – sometimesLazy Jun 17 '20 at 18:51
0

Your classA type needs to define an operator<. Notice that std::pair compares lexicographically.

Sebastian Hoffmann
  • 2,815
  • 1
  • 12
  • 22