Sign in to follow this  
utilae

Std Sort, how to sort by ___

Recommended Posts

Hi, I am using C++. I have a vector m_vecItems that is full of class item. Class item has various properties, eg Type, Name, etc I have been using std Sort() to sort vectors before, but now I need to sort my vector by one of Class items properties eg Sort(m_vecItems, ascending, by Item.Type) How do I do this ?

Share this post


Link to post
Share on other sites
You create a function that performs the comparison for you, and pass that to the sort algorithm. This shows a few examples of how to do that. You can use a raw function as well.


bool compare(MyClass a, MyClass b)
{
return a.blah < b.blah;
}

sort(vec.begin(), vec.end(), compare);


Share this post


Link to post
Share on other sites
You'll typically want to use const references for your comparison function to avoid unneeded copy constructors (depending on what your sorting this can be a couple of times faster, and you only change need to change your function inputs).

bool compare(const MyClass &a,const MyClass &b)
{
return a.blah < b.blah;
}

A functor may give also give a minor speed boost.

Share this post


Link to post
Share on other sites

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