Sign in to follow this  

Multi-sorting?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi! Is there any way to sort an std::list array based on several criterias? Say, if I wanted to sort the list based on primarly Type, and secondary Radius ? I know I can loop through the primarly sorted list and then re-sort each Type-segment based on Radius but it would be nice if one function could do it all. Is it possible? /Robert

Share this post


Link to post
Share on other sites
struct sort_predicate
:
public std::binary_function< object const, object const, bool >
{

bool operator()(object const & lhs, object const & rhs) const
{
if (lhs.criteria_1 != rhs.criteria_1)
{
return lhs.criteria_1 < rhs.criteria_1;
}
if (lhs.criteria_2 != rhs.criteria_2)
{
return lhs.criteria_2 < rhs.criteria_2;
}
// ...
return lhs.criteria_n < rhs.criteria_n;
}

};

objects.sort(sort_predicate());
Σnigma

Share this post


Link to post
Share on other sites
std::list::sort takes a predicate, which can be defined as a functor:

struct Example
{
int type;
float radius;
};

struct Sorter
{
bool operator()(const Example &one, const Example &two) const
{
return // something based on type and radius
}
};

int main()
{
std::list<Example> list;
list.sort(Sorter());
}




Make sure your sort functor imposes a Strict Weak Ordering.

Share this post


Link to post
Share on other sites
Hi!

Thanks, got it working!


bool SceneGraph::largestRadiusFirst(const SceneEntity &A,const SceneEntity &B)
{
if (A->type != B->type)
return A->type < B->type;
if (A->boundingbox.radius != B->boundingbox.radius)
return A->boundingbox.radius > B->boundingbox.radius;
};

list.sort(SceneGraph::largestRadiusFirst);




Cheers!

/Robert

Share this post


Link to post
Share on other sites
Another option, which may be appropriate (hard to tell with the info you've given) is to use boost::multi_index_container<>, which lets you keep your data sorted according by multiple predicates at once.

If you're having to sort your list a little too often for comfort, or if sorted-ness is an invariant you'd like to maintain, it would be worth your while checking out this library.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this