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.
This operator
allows you to compare a
Bon the LHS against aB*on the RHS. You are trying to compare withB*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(orconst B&) and de-referencing your pointers at the point of comparison: