Jump to content
  • Advertisement
Sign in to follow this  
utilae

Std Sort, how to sort by ___

This topic is 4483 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, 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
Advertisement
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
You can also consider usign a library that lets you type the code in-line. Take a look at two different Boost libraries: Spirit:Phoenix and Lambda. Here's a Phoenix example of finding the first odd integer in an STL container:

find_if(c.begin(), c.end(), arg1 % 2 == 1)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!