Jump to content
  • Advertisement
Sign in to follow this  
suliman

sorting std::vector

This topic is 4487 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
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

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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!