Sign in to follow this  

sorting std::vector

This topic is 4276 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4276 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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