Sorting an STL Vector by my own compare function?
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
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>() );
You need to use std::sort, like this :
That should do it.
<edit :: Right, what Fruny said. ;)
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. ;)
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:
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);}
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>
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement