2

I don't really have a very good understanding to how STL works.

I was able to create a list and add items to it.

But now I can't seem to search through the list to find an element with a desired property.

Forgive my ignorance on this. I am very new to STL and I still struggle with some elements of C++.

Here is the code. I know it produces errors , but I would like something like this.

Thanks in advance.

extern list<MonsterClass> Monsters;

MonsterClass FindMonster(int x)
{
     MonsterClass Monster;
     list<MonsterClass>::iterator ListItem;

      for(ListItem = Monsters.begin(); ListItem != Monsters.end(); ++ListItem) 
      {
      if (ListItem.X == x)
         {
           Monster = ListItem;
           return Monster;
         }
      }

   return NULL;
}

3 Answers 3

7

You are confusing elements and iterators. Iterators are placeholders for positions in the list, they are not the elements themselves. To get to the element, you need to dereference an iterator:

if ((*ListItem).X == x) // or, easier: if(ListItem->X == x)
   {
     Monster = *ListItem;
     return Monster;
   }
}

Furthermore, you cannot return NULL since your Monster class cannot take the value NULL (which is a pointer). What you can do is return an iterator instead of the item itself. Then your function does almost exactly the same as the std::find function from the <algorithm> standard header.

0
3
// C++03
struct by_X {
   by_X( int x ) : x(x) {}
   bool operator()( Monster const & m ) const {
      return x == m.X;
   }
   const int x;
};
std::find_if( Monsters.begin(), Monsters.end(), by_X( 5 ) );

If your compiler has lambda (c++0x) support:

std::find_if( Monsters.begin(), Monsters.end(), [=x]( Monster const & m ) { return m.X == x; } );
1

If you want to do this very often (like, unless it's just for debugging or something like that), a list probably isn't the best choice for the job. Just for one obvious alternative, a std::set directly supports searching like this. In a set the search will normally be quite a bit faster as well (logarithmic instead of linear complexity).

1
  • I will try the set idea. Thanks :)
    – Greycrow
    Mar 29, 2011 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.