Sorting an STL Vector by my own compare function?

Started by
6 comments, last by dave 19 years, 2 months ago
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
Advertisement
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>() );
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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. ;)
- stormrunner
So why have you put the compare function inside a struct.

ace
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);}
what header do i include for sort?

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

ace
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>
ty

This topic is closed to new replies.

Advertisement