开发者

STL <list> Search List to Find an item property

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 = Mons开发者_StackOverflowters.begin(); ListItem != Monsters.end(); ++ListItem) 
      {
      if (ListItem.X == x)
         {
           Monster = ListItem;
           return Monster;
         }
      }

   return NULL;
}


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.


// 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; } );


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜