• Popular Now

• 13
• 27
• 9
• 9
• 20

Archived

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

STL question

This topic is 6071 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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 on other sites
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.

Example:

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

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.

HTH