tags:

views:

64

answers:

2

I have a function of a "Table" class that should add a player to the table. I decided that if the seat is taken, the function should try and go through all the seats and add the player to the next available seat. How do I implement this in my addPlayer function?

int Table::addPlayer(Player player, int position)
{
deque<Player>::iterator it;

if(playerList[position] != "(empty seat)") {
    //What goes here?
}
playerList.put(player,it);
cout >> "Player " >> player.toString >> " sits at position " >> position >> endl;

}

+2  A: 

Instead of using position, use the iterator to point to that position, using something like this:

it = playerList.begin() + position;

Then, check if the seat is taken using the iterator. If the seat is taken, increment the iterator, but check for end, like this:

while (no empty seat found yet)
   {
   ++it;
   if (it==playerList.end()) it = playerList.begin();
   }

Of course, if all seats have been taken, this will result in an endless loop. Therefore, also keep the iterator you started from (let's call this itStart), and add a check on it:

while (no empty seat found yet)
   {
   ++it;
   if (it==playerList.end()) it = playerList.begin();
   if (it==itStart) break;       // We tried all seats
   }
Patrick
Thanks Patrick. Is your first code block legal C++? Can I add an int to an iterator, and then assign that to an iterator?
George
In case of a random access iterator, yes. For more information, see http://www.cplusplus.com/reference/std/iterator/RandomAccessIterator/
Pieter
@George: yes, as long as the iterator supports `operator+(int)`. Random-access iterators must do this (the actual overload is for `difference_type`, but int implicitly converts) and deque must have a random-access iterator.
Steve Jessop
@George, at the moment I wrote this I wasn't sure, but I thought the line would be enough to get you started. Thanks, Pieter and Steve for clarifying that this is indeed possible.
Patrick
A: 

Maybe you should also take a look at the circular buffer from boost.

http://www.boost.org/doc/libs/1_43_0/libs/circular_buffer/doc/circular_buffer.html

I think it will do what you want, and is quite easy to use.

mkaes