469,910 Members | 1,468 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,910 developers. It's quick & easy.

sorting with STL containers containing objects of different subclasses

Hi!

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
class).
Base
+--Der1
+--Der2

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
object.

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
Jul 19 '05 #1
1 3571
"Victor Bazarov" <v.********@attAbi.com> wrote in message
news:vg************@corp.supernews.com...
"Koen" <no@ssppaamm.com> 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
{
public:
bool operator()(const Base* inEvent1,const Base* inEvent2)
{
return (inEvent1->GetTimeStamp() < inEvent2->GetTimeStamp()) ? true :
false;
}
};

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!

Koen
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

31 posts views Thread by John Roth | last post: by
18 posts views Thread by Matthias Kaeppler | last post: by
14 posts views Thread by JoeC | last post: by
3 posts views Thread by SneakyElf | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.