简体   繁体   中英

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 ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM