I am writing a program in C++ and I would like to define priority queue of one of my class. I need it to compare objects by one of the class member variable. I have used an operator< overload, but I know there is a second way to achieve this goal – special function defined with queue definition. Which way is better, more esthetic and more efficient? And how to write such a function?
I have done it as follows:
#include <iostream>
#include <queue>
using namespace std;
class Human {
public:
string name;
int age;
Human(string name, int age);
};
Human::Human(string name, int age) : name(name), age(age) {}
bool operator<(Human a, Human b) {return a.age < b.age ? true : false;}
int main() {
Human p1("Child",5);
Human p2("Grandfather",70);
Human p3("Older son",20);
Human p4("Father",40);
Human p5("Younger son",10);
priority_queue<Human> Q;
Q.push(p1);
Q.push(p2);
Q.push(p3);
Q.push(p4);
Q.push(p5);
while(!Q.empty()) {
cout << "Name: " << Q.top().name << ", age: " << Q.top().age << endl;
Q.pop();
}
return 0;
}
Style
If your type has an intrinsic, “natural” ordering, it is reasonable to express that with a built-in operator.
If the ordering varies by how you’re using the type (eg. you have one collection of Human sorted by age, one by height, one by IQ), then it seems sensible to say the ordering is a property of the container instead of the type.
Implementation
You can write a free function, or use a functor if you need state.
Note that these are both exactly as amenable to inlining as a built-in operator, so there is no inherent difference in speed (it’s probably harder for the compiler to prove a function pointer is inline-able though, so functors are generally preferred).