I'm trying to understand how comparator works for priority queue, I did several tests:
Test 1: Create comparator class, and use priority_queue<T, vector<T>, cmp>
It always works fine
Test 2:
struct test {
int a = 0;
};
bool operator<(const test& lhs, const test& rhs) {
return lhs.a < rhs.a;
}
int main()
{
priority_queue<test> pq;
}
This works as expected.
Test 3: Put test 2 inside a class
class T{
struct test {
int a = 0;
};
bool operator<(const test& lhs, const test& rhs) {
return lhs.a < rhs.a;
}
};
Compiling Error:
'bool T::operator<(const T::test&, const T::test&)' must take exactly one argument
It seems that the compiler thought that I was overloading the operator < for class T. Is there any other ways to accomplish this if I really need the classes to be nested?
Test 4: Overload operator<
struct test {
int a = 0;
bool operator<(const test& rhs) {
return a < rhs.a;
}
};
int main()
{
vector<test> v;
sort(v.begin(), v.end()); // No error
set<test> s; // No error
priority_queue<test> pq; // Compiling error
}
Only priority_queue throws an error:
'passing 'const test*' as 'this' argument discards qualifiers'
I don't know why this works for sort and set but not for priority queue.
operator<a method ofT. Either declare it insideT::testas a friend, or declare it outsideTentirely.constbefore the{. And Please ask one question per question.