Velocity Reviews

Velocity Reviews (
-   C++ (
-   -   sorting with STL containers containing objects of different subclasses (

Koen 06-30-2003 03:19 PM

sorting with STL containers containing objects of different subclasses

I have a vector containing the following:

vector<Base*> theVector;
theVector.push_back(new Der1());
theVector.push_back(new Der1());
theVector.push_back(new Der2());
theVector.push_back(new Der2());

where the Der1 and Der2 classes are derived from Base (abstract base

Each class derived from Base contains a "time stamp" and I have
implemented the operator: bool Base::operator<(const Base& inEvent)
const; that compares the time stamp of the object with that of the given

Now, I would like to sort theVector according to the time stamp.
If I just call sort(theVector.begin(),theVector.end()); this doesn't
work because the "<" operator is never called (in fact, the addresses of
the objects in the list are compared directly).
Is there a way to have both things with STL containers:
1. store different object types (all derived from a single base class)
in a container (the only way to do this is to store pointers; otherwise
the objects get "sliced")
2. be able to use the standard algorithms on these containers

This must be possible, but I can't seem to find out how right now.
Any help appreciated!


Koen 06-30-2003 03:51 PM

Re: sorting with STL containers containing objects of different subclasses
"Victor Bazarov" <> wrote in message
> "Koen" <> wrote...

> You need to define the comparator:
> bool myLessFunc(const Base* p1, const Base* p2)
> {
> return *p1 < *p2; // uses your operator<
> }
> And pass it to the sort function:
> sort(theVector.begin(), theVector.end(), myLessFunc);
> Victor

Thanks a lot Victor!

I had in the meantime found something about using functors for these
things, something like:

class CompareFunctor
bool operator()(const Base* inEvent1,const Base* inEvent2)
return (inEvent1->GetTimeStamp() < inEvent2->GetTimeStamp()) ? true :

But your solution is much simpler and I use that now (although I did add
the function myLessFunc to my Base class as a static member function,
for when I would need it at other places too).
Thanks for the very (really very) fast reply!


All times are GMT. The time now is 07:34 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.