I have a class named Customer which is overloading the < operator:
bool Customer::operator<(const Customer &other) {
return this->price < other.price;
}
but when I try to initialize the priority queue I get pages of errors.
Customer c1(10,5,12,30);// last parameter is price
Customer c2(10,5,12,2);
priority_queue<Customer , vector<Customer> , less<Customer> > barQ;
barQ.push(c2);
barQ.push(c1);
cout<<barQ.top().price;
Then, i accidentally found out that when i initialize it in following way:
Customer c1(10,5,12,30);
Customer c2(10,5,12,2);
priority_queue<Customer* , vector<Customer*> , less<Customer*> > barQ;
barQ.push(&c2);
barQ.push(&c1);
cout<<barQ.top()->price;
I got no errors and it works well. So my question is that what's the difference between Customer & Customer*? I thought it should work when I declare it with Customer, NOT Customer* , why it works otherwise?
The signature of std::less::operator()
is (taken from cppreference):
bool operator()( const T& lhs, const T& rhs ) const; // (until C++14) constexpr bool operator()( const T& lhs, const T& rhs ) const; //(since C++14)
Note the it takes both parameters as const
, thus it can only call a const
operator<
:
bool Customer::operator<(const Customer &other) const { // <--- add const here
return this->price < other.price;
}
Your second code is not really doing what you want it to do, because it uses the built-in operator<
for pointers.