Sort a list of pointers.

Posted by YuppieNetworking on Stack Overflow See other posts from Stack Overflow or by YuppieNetworking
Published on 2010-03-31T15:53:04Z Indexed on 2010/03/31 16:03 UTC
Read the original article Hit count: 206

Filed under:
|
|
|

Hello all,

Once again I find myself failing at some really simple task in C++. Sometimes I wish I could de-learn all I know from OO in java, since my problems usually start by thinking like Java.

Anyways, I have a std::list<BaseObject*> that I want to sort. Let's say that BaseObject is:

class BaseObject {
protected:
    int id;
public: 
    BaseObject(int i) : id(i) {};
    virtual ~BaseObject() {};
};

I can sort the list of pointer to BaseObject with a comparator struct:

struct Comparator {
    bool operator()(const BaseObject* o1, const BaseObject* o2) const {
        return o1->id < o2->id;
    }
};

And it would look like this:

std::list<BaseObject*> mylist;
mylist.push_back(new BaseObject(1));
mylist.push_back(new BaseObject(2));
// ...

mylist.sort(Comparator()); 

// intentionally omitted deletes and exception handling

Until here, everything is a-ok. However, I introduced some derived classes:

class Child : public BaseObject {
    protected:
    int var;
    public: 
    Child(int id1, int n) : BaseObject(id1), var(n) {};
    virtual ~Child() {};
};

class GrandChild : public Child {
    public:
    GrandChild(int id1, int n) : Child(id1,n) {};
    virtual ~GrandChild() {};
};

So now I would like to sort following the following rules:

  1. For any Child object c and BaseObject b, b<c
  2. To compare BaseObject objects, use its ids, as before.
  3. To compare Child objects, compare its vars. If they are equal, fallback to rule 2.
  4. GrandChild objects should fallback to the Child behavior (rule 3).

I initially thought that I could probably do some casts in Comparator. However, this casts away constness. Then I thought that probably I could compare typeids, but then everything looked messy and it is not even correct.

How could I implement this sort, still using list<BaseObject*>::sort ?

Thank you

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl