Once again, I find myself unsuccessful in some really simple C ++ task. Sometimes I would like to know everything that I know from OO in java, since my problems usually start with thinking like Java.
Anyway, I have std::list<BaseObject*> that I want to sort. Say BaseObject :
class BaseObject { protected: int id; public: BaseObject(int i) : id(i) {}; virtual ~BaseObject() {}; };
I can sort the list of pointers to BaseObject with a comparator structure:
struct Comparator { bool operator()(const BaseObject* o1, const BaseObject* o2) const { return o1->id < o2->id; } };
And it will look like this:
std::list<BaseObject*> mylist; mylist.push_back(new BaseObject(1)); mylist.push_back(new BaseObject(2));
So far, everything is in order. 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 the following rules:
- For any
Child c object and BaseObject b , b<c - To compare
BaseObject , use its id s, as before. - To compare
Child objects, compare it to var s. If they are equal, return to rule 2. GrandChild objects must depart from Child behavior (rule 3).
At first I thought that maybe I could make some throws in Comparator . However, this discards constancy. Then I thought that maybe I could compare typeid s, but then everything looked messy, and that wasn't even right.
How could I implement this view using list<BaseObject*>::sort ?
thanks
c ++ sorting pointers stl
Yuppie network
source share