I would like to implement two overloaded versions of a compare function for instances of an example class. One of them gets pointer parameters and another one gets reference objects.
class MyClass
{
public:
int x;
};
bool compare(MyClass *p1, MyClass *p2)
{
return p1->x < p2->x;
}
bool compare(MyClass &p1, MyClass &p2)
{
return p1.x < p2.x;
}
I test it using the following statements and it seems that C++ can select a proper version of compare:
MyClass *p1 = new MyClass;
MyClass *p2 = new MyClass;
p1->x = 1; p2->x = 2;
MyClass p3;
MyClass p4;
p3.x = 2; p4.x = 1;
cout << compare(p1, p2) << endl;
cout << compare(p3, p4) << endl;
However, when I try to use them in the sort function, the compiler complains that "no matching function" can be found.
vector<MyClass*> v;
for (int i = 0; i < 9; i++)
{
MyClass *temp;
temp = new MyClass; temp->x = 9 - i;
v.push_back(temp);
}
vector<MyClass> v2;
for (int i = 0; i < 9; i++)
{
v2.push_back(*v[i]);
}
for (auto i : v) cout << i->x;
cout << endl;
for (auto i : v2) cout << i.x;
cout << endl;
sort(v.begin(), v.end(), compare);
for (auto i : v) cout << i->x;
cout << endl;
sort(v2.begin(), v2.end(), compare);
for (auto i : v2) cout << i.x;
cout << endl;
The problem is only with finding the proper version of the overloaded function because when I change the name of the second compare to compare2 and use it in the second call of sort everything works fine.
Can someone explain why it is not working and possibly suggests a solution without choosing different names for functions.