Sign in to follow this  
dave

Sorting an STL Vector by my own compare function?

Recommended Posts

How do i do this. I had code demonstrated to me whereby you call a list.sort() function that takes 1 parameter that is ur compare function. But there is no .sort() function available for a vector. How would u suggest i sort like this. BTW I want to sort by my own compare function because the item that i am sorting by is being pointed to by the item in the vector. ace

Share this post


Link to post
Share on other sites
Quote:
Original post by ace_lovegrove
But there is no .sort() function available for a vector.


That's because std::sort() works perfectly fine on a std::vector.

e.g. std::sort(vec.begin(), vec.end(), std::greater<Foo>() );

Share this post


Link to post
Share on other sites
You need to use std::sort, like this :

struct SortFunc {
bool operator () (mvecobj& o1, mvecobj& o2) {
return o1.val > o2.val;
}
};

void sortMeObjs() {
std::vector<mvecobj> m_list;
// fill list with stuff
// call std::sort with sort method
std::sort(m_list.begin(), m_list.end(), SortFunc());
}



That should do it.

<edit :: Right, what Fruny said. ;)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Stormrunner used operator(). In that case you must capsulate it into a class or a struct, otherwise it would replace the default sorting method.

You can make your own custom sorting function also this way:


bool MyOwnSort(mvecobj& lhs, mvecobj& rhs)
{
return (lhs.val > rhs.val)
}

void f()
{
vector<mvecobj> vList;
sort(vList.begin(), vList.end(), MyOwnSort);
}

Share this post


Link to post
Share on other sites
Quote:
Original post by ace_lovegrove
what header do i include for sort?

I tried including algo and it didnt find it :( hehe

ace


#include <algorithm>

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