sorting with STL containers containing objects of different subclasses

K

Koen

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::eek:perator<(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
 
K

Koen

Victor Bazarov said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top