sorting std::vector
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
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.
...and then sort the vector...
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...
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
So i add that operator to the guy-class. But how do i call the sort, exactely to make this work?
Erik
Isn't it:
Don't know exactly how stl-sort works, but it may be some type of quick sort i think...
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.
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.
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
Very Simple Sort Example http://www.msoe.edu/eecs/cese/resources/stl/sort.htm
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement