Roland Sams
Roland Sams

Reputation: 173

Pointers with STL maps and lists

I did do a good search on the 'net about this and turned up lots of help regarding vectors but not really anything on STL lists. I am attempting to erase a pointer from a list within a map. (a little tricky). I really want to use pointers and not revert to another (worse) system of doing things. I will show the code

bool RoomDB::removePlayer( int socketid, int roomid )   {

list<GamePlayer>::iterator itit;

 for( itit == roomlist[roomid].playerlist.begin(); itit != itit.end(); itit++ ) {
    if( itit.socketno == socketid )
    itit.erase( itit );
}

Upvotes: 0

Views: 88

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477010

I think it should just be like this:

roomlist[roomid].playerlist.remove_if(
    [socketid](GamePlayer const & gp) { return gp.socketno == socketid; }
);

If you don't have lambdas, you'll have to write a little predicate yourself, or you go the manual way; but now beware of the loop:

for (std::list<GamePlayer>::iterator it = roomlist[roomid].playerlist.begin();
     it != roomlist[roomid].playerlist.end();  /* no increment */ )
{
   if (it->socketno == socketid)
   {
     it = roomlist[roomid].playerlist.erase(it);
   }
   else
   {
     ++it;
   }
}

Upvotes: 3

Seth Carnegie
Seth Carnegie

Reputation: 75130

There are a bunch of things wrong. I will try to list all of them, though I may miss some:

  1. It should be list<GamePlayer*>::iterator itit; if, as you say, your lists contain pointers
  2. It should be itit = roomlist[roomid].playerlist.begin();, not itit = ..., like KerrekSB said
  3. It should be itit != roomlist[roomid].playerlist.end(), not itit != itit.end()
  4. It should be if( (*itit)->socketno == socketid ), not if( itit.socketno == socketid ) (again, if your list contains pointers)
  5. It should be roomlist[roomid].playerlist.erase(itit), not itit.erase(itit).

Upvotes: 0

Related Questions