Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find operator< for pointer type

Tags:

c++

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.

like image 260
gcandal Avatar asked Jun 12 '26 07:06

gcandal


1 Answers

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--)
like image 170
juanchopanza Avatar answered Jun 15 '26 10:06

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!