I am trying to create a simple priority queue containing elements of class c.
The most intuitive ways seemed to be the first one, however, it gave me compile error.
Then, I tried both second and third ways, and they worked just fine.
To sum up, why the first method does not work? And, should we use one way over the others, and why?
class c {
public:
int data;
c(int n):data(n){};
// First way : putting comparator inside class
bool operator<(c a) {
return data < a.data;
}
};
// Second way : putting comparator outside
bool operator<(c a, c b) {
return a.data < b.data;
}
// Third way : creating a comparator class
struct Compare {
bool operator()(c a, c b) {
return a.data < b.data;
}
};
int main(){
priority_queue<c> pq;
priority_queue<c, vector<c>, Compare> pq; // only for third method
pq.push(c(3));
pq.push(c(1));
pq.push(c(2));
pq.push(c(4));
while (pq.size()) {
cout << (pq.top().data);
pq.pop();
}
}