arjacsoh
arjacsoh

Reputation: 9262

"Vector erase iterator out of range" in C++

In this C++ code I try to erase element from the end of the vector but the program stops and I receive the message: Expression: vector erase iterator outside range.

What is the problem? After all is by this code the vector a vector of pointers or the way I pass them in push_back inserts only a copy of pointer?

int _tmain(int argc, _TCHAR* argv[])
{
    vector<Player*> allPlayers;
    allPlayers = createPlayers();

    int numPlayers;

    cout<<"Vector size: "<<allPlayers.size();
    cout<<endl;
    cout<<"How many players are involved in the game(1-4)?\n";
    cin>>numPlayers;
    cout<<endl;
    allPlayers.erase(allPlayers.end());

    return 0;
}


vector<Player*> createPlayers(){

    Player *Player1 = new Player(1,1500);
    Player *Player2 = new Player(2,1500);
    Player *Player3 = new Player(3,1500);
    Player *Player4 = new Player(4,1500);


    vector<Player*> allPlayers;
    allPlayers.push_back(Player1);
    allPlayers.push_back(Player2);
    allPlayers.push_back(Player3);
    allPlayers.push_back(Player4);


    return allPlayers;
}

Upvotes: 4

Views: 15176

Answers (2)

balki
balki

Reputation: 27694

Use pop_back member function. As said already, end does not give you the iterator for the last element but one past the last element.

http://en.cppreference.com/w/cpp/container/vector/pop_back

Why do you want to create pointers of Player?

Modify the code as follows,

In main,

vector<Player> allPlayers;
createPlayers(allPlayers);

In createPlayers function:

void createPlayers(vector<Player>& allPlayers)
{
    Player Player1(1,1500);
    Player Player2(2,1500);
    allPlayers.push_back(Player1);
    allPlayers.push_back(Player2);
    return;
}

Upvotes: 2

Mysticial
Mysticial

Reputation: 471569

.end() returns the iterator one past the last element. That's why you're getting that error. You want the iterator to point to the last element. Not one-past the last element.

So try changing the line to:

allPlayers.erase(allPlayers.end() - 1);

And make sure that you properly handle the case where vector is empty.


Alternatively you could use .pop_back(), but in either case, you're gonna want to deal with the memory leaks as well as mentioned in the comments.

Upvotes: 9

Related Questions