This topic is now archived and is closed to further replies.


STL question

Recommended Posts

Orbitalx    122
I haven''t used the STL all that much, and I''m having a little trouble figuring out how to sort a list.. I have a list of (Object*), which I want to sort according to one of their member values, in this case, the Z-order.. How would I go about doing that? Thanks, Orbitalx

Share this post

Link to post
Share on other sites
JungleJim    122
You have to provide a binary predicate (a function object) that compares two Object*s, and returns a boolean indicating if the first parameter is smaller than the second.


struct less_than {
bool operator()(Object* x, Object* y) { return x->z < y->z; }
// ...
list l;

It is important that if two objects compared are equal, less_than() returns false. The function object may look weird, but it''s quite handy. It''s a class that only defines a operator() method, which takes two parameters (the types in the container), and returns a bool.

Please note that list::sort is used, and not the sort defined in <algorithm>. That is because a list doesn''t provide random access iterators, which are required for the std::sort algorithm. In general, if a container provides a member function for a certain algorithm (like sort), you should use that member instead of the ''global'' algorithm.


Share this post

Link to post
Share on other sites