Sign in to follow this  
Ezbez

list.sort() for user-made classes

Recommended Posts

I need to sort my std::list in ascending order based on a class member. I overloaded the operator '<' so that I can use the list.sort() function, however, its not working. Heres some selected code from what I did:
std::list<enemy *> enemies;
int main(int argc, char *argv[])
{
  //fill enemies

  enemies.sort();//sort enemies
    for (std::list<enemy*>::iterator itr = enemies.begin(); itr != enemies.end(); ++itr)
    {
        enemy *obj = *itr;
        printf("%d\n",obj->getInteger() );//print their integer one at a time
    }
}

int enemy::operator<(enemy &e)
{
   if(this->getInteger() < e->getInteger() )
   {
     return 1;
   }
   else
   {
     return 0;
   }
}

It compiles without a problem. but it doesn't print them out in order numerically, merely in the order that they where created. Anyone know what I am doing wrong and how to fix it? Thanks in advanced, Ezbez

Share this post


Link to post
Share on other sites
You have a list of pointers, so the operator<() overload won't be used. Instead you can create a free function that compares enemy pointers and pass that to list::sort() (provided your compiler groks templated member functions).
ex:

bool compare(const enemy * lhs, const enemy * rhs) {
return (lhs->getInteger() < rhs->getInteger() );
}

enemies.sort(&compare);

Share this post


Link to post
Share on other sites
You have a list of enemy pointers, so the list will use operator < (enemy*, enemy*), which compares the addresses of the objects. I think std::list::sort takes a comparison function:

std::list<enemy *> enemies;
enemies.sort(sort_by_number());

struct sort_by_number {
bool operator () (enemy* a, enemy* b) {
return a->getInteger() < b->getInteger();
}
};

Also, operator < should return a bool, not an int (although int will work), and "if(condition) return true; else return false;" is the same as "return condition;"

Share this post


Link to post
Share on other sites
It doesn't work becuase you list holds pointers to enemy, not enemy. So it sorts the pointers (which will very likely be allocated inorder). I think you need to use a functor or function pointer that takes enemy pointers to sort it. I'll write something up in a minute.

Edit: nm just use the ones posted above.

Share this post


Link to post
Share on other sites

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