Reputation: 957
I'm trying to order a vector of pointers using insertion sort with an overloaded < operator (cannot use any library). Having a class which contains another, something like:
class A {
vector<B*> v;
void order();
}
class B {
int id; //each one is unique
virtual double num() {} const;
bool operator<(const B* b2) const;
}
class B1: public B {
double num() {} const;
}
class B2: public B {
double num() {} const;
}
Each child has a different way of calculating num, and the sorting is done using the double returned by num as first criteria, and then id. (sorry for the indentation)
void A::order() {
for (unsigned int p = 1; p < v.size(); p++)
{
ClassB* tmp = v[p];
int j;
for (j = p; j > 0 && tmp < v[j-1]; j--) // Error on this line
v[j] = v[j-1];
v[j] = tmp;
}
}
bool B::operator<(const B* b2) const {
cout << "Operator <\n";
if(this->num()!=b2->num())
return this->num()<b2->num();
return id<d2->id;
}
I can't understand why the operator isn't being called when trying to compare the 2 pointers.
Upvotes: 3
Views: 312
Reputation: 227468
This operator
bool operator<(const B* b2) const;
allows you to compare a B
on the LHS against a B*
on the RHS. You are trying to compare with B*
on both sides, so the operator doesn't apply.
You cannot overload the pointer comparison operators, so one solution could be to compare in terms of B
(or const B&
) and de-referencing your pointers at the point of comparison:
for (j = p; j > 0 && *tmp < *v[j-1]; j--)
Upvotes: 6
Reputation: 258618
You can't overload an operator to compare pointers. And even if you could, it would still be illegal most of the time. You can only compare pointers that point to memory inside the same array, or one position after the end of the array. Anything other than that is undefined behavior.
Your B::bool operator<(const B* b2) const;
should actually be bool operator<(const B& b2) const;
. This allows you to compare 2 B
objects, instead of an object and a pointer to an object - which is what your code does now.
If you have to sort a container of pointers, you can provide a compare function as callback that takes 2 pointers as parameters, but implementing operator<
as a member with a pointer as parameter doesn't make sense.
Upvotes: 3