list.sort() for user-made classes

Started by
3 comments, last by Ezbez 18 years, 5 months ago
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
Advertisement
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);
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;"
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.
Thanks guys, that really helped! It now works.

This topic is closed to new replies.

Advertisement