sorting std::vector

Started by
6 comments, last by suliman 18 years ago
i know this has been asked before, but ive never gotten it to work. lets say i have class guy{ public: int posX; int posY; }; i have a std::vector of them. I wanna sort it so that lowest posX is first. How must i write the call to ->sort(...) so it works? When i do it nothing happens. Thanks a lot E
Advertisement
Quote:Original post by suliman
When i do it nothing happens.

I'm sure something happens.

The simplest solution is to provide operator< for your class.

CM
I've done this, but it was a long time ago, but i'll post what i think it should be...but basically i'm just pulling things out of my ass... =)

I think you have to overload the "<" operator.
class CGuy{public:    int posX;    int posY;    bool operator<(const CGuy &g) { return this.posX < g.posX; }};


...and then sort the vector...
----------------------------------------------------------------------------------------------------------------------"Ask not what humanity can do for you, ask what you can do for humanity." - By: Richard D. Colbert Jr.
ok. i dont fully understand, but im on my way!

So i add that operator to the guy-class. But how do i call the sort, exactely to make this work?

Erik
#include <algorithm>std::vector<CGuy> guys;// ...std::sort(guys.begin(), guys.end());

std::sort
Isn't it:
class CGuy{public:    bool operator<(const CGuy &g) { return this.x_pos < g.x_pos; }    int x_pos;    int y_pos;};std::vector<CGuy> guyList;std::sort(guyList.begin(), guyList.end());


Don't know exactly how stl-sort works, but it may be some type of quick sort i think...

Quote:ok. i dont fully understand, but im on my way!

Ok so why do you have to overload the operator...
How do you sort a list of numbers? Simple, you compare the numbers, and put the smallest first and the biggest at the end. But how do you sort something of a class type? You have to overload the operator to tell the sort function what you want to compare.
----------------------------------------------------------------------------------------------------------------------"Ask not what humanity can do for you, ask what you can do for humanity." - By: Richard D. Colbert Jr.
Operator Overloading Tutorial http://cma.zdnet.com/book/c++/htm/ch10.htm#Heading3

Very Simple Sort Example http://www.msoe.edu/eecs/cese/resources/stl/sort.htm
cool.

ill try it at home.

Erik

This topic is closed to new replies.

Advertisement