Sign in to follow this  

sorting standard list?

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

Hi I know this is a bore but I found out that i dont know how to sort a standard template c++ list... Seems to do not find any clear examples of it. My list consist of <unit *> (pointers to a unit-class) I want it to sort the pointer in the list regarding a value (int bodyX) of the units these pointers point to. But how? Thanks a bunch Suliman, Sweden

Share this post


Link to post
Share on other sites
First create a function or function object that compares unit pointers how you want. Ex:

bool compare_body_x(const unit * lhs, const unit * rhs) {
return lhs->bodyX < rhs->bodyX;
}

Then pass the function or function object to std::list::sort(). This may not work if you are using an older compiler like MSVC6.

Share this post


Link to post
Share on other sites
I do as you say and then to sort i run

unitList.sort(compare_body_x); // was that right?

but it gives me:
"cannot convert par 1 from ... to struct std::greater<class unit *>

Running sort() as a "free-function" it wants 2 parameters, but i think my example above is closer to the sollution right? But what am I doing wrong?

my editor is microsoft virtual c++ 6.0. Is that to old to sort a list? Dont get it.



EDIT:
I cannot post i reply... Gets me back to forum overview. So I edit and hope someone sees this.

I try this but i cannot get it to work. Has noone manages to sort a std::list for visual c++ and can post that code? Would be great.


Suliman

[Edited by - suliman on October 8, 2005 12:47:25 PM]

Share this post


Link to post
Share on other sites
Visual C++ 6 can handle sort algorithm; with different algorithms it uses ugly hacks to have them working.
The idea proposed by SiCrane is right but, as he wrote, you need to adapt it for the crappy compiler.
Go in the help inline or in some header file ( <algorithm> ? ) and copy the body of the "predicate" less. It will work.

Share this post


Link to post
Share on other sites

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