Search code examples
c++iteratorerase

Issue erasing an element from a list in c++


I have the following code:

list<Item> playerItems = player.GetPlayerItems();

        list<Item>::iterator iterator;
        for (iterator = playerItems.begin(); iterator != playerItems.end(); ++iterator)
        {
            if (itemToSell == (*iterator).GetName())
            {
                if ((*iterator).GetCost() < GetShopGold())
                {
                    SetShopItem(*iterator);
                    SetShopGold(GetShopGold() - (*iterator).GetCost());

                    player.SetPlayerGold(player.GetPlayerGold() + (*iterator).GetCost());

                    //The issue is here
                    iterator = player.GetPlayerItems().erase(iterator);
                    return true;
                }
                else
                {
                    cout << "I can't afford that..." << endl;
                }
            }
        }

This is the RemovePlayerItem code:

void Player::RemovePlayerItem(list<Item>::iterator& iterator)
{
    iterator = _playerItems.erase(iterator);
}

When I run the code, I get the following error:

_DEBUG_ERROR("list erase iterator outside range");

I've googled it and it seems to be related to my iterator, but I'm not sure of the relationship between the error and the iterator.

In contrast, if I make the _playerItems variable a global one and then start/end the iterator using this global variable, the code runs fine if I use the following code iterator = player._playerItems.erase(iterator);

EDIT

This is GetPlayerItems() function

list<Item> Player::GetPlayerItems()
{
    return _playerItems;
} 

Can anyone point me in the right direction with this?


Solution

  • iterator is an iterator into playerItems. It's not clear what player.GetPlayerItems() returns (since you neglected to show its definition or even a declaration), but whatever it is, playerItems is a separate, distinct list - a copy of what GetPlayerItems() returned.

    You are then trying to erase from one list using an iterator pointing into the other. This exhibits undefined behavior - someList.erase(iter) expects iter to be a valid iterator into someList.