简体   繁体   English

在C ++中“向量擦除迭代器超出范围”

[英]“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. 在这个C ++代码中,我尝试从向量的末尾擦除元素但是程序停止并且我收到消息: 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? 毕竟通过这个代码向量一个指针的向量或我在push_back中传递它们的方式只插入一个指针的副本?

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

.end() returns the iterator one past the last element . .end()返回一个超过最后一个元素的迭代器。 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. 或者你可以使用.pop_back() ,但在任何一种情况下,你都会想要处理内存泄漏以及评论中提到的内容泄漏。

Use pop_back member function. 使用pop_back成员函数。 As said already, end does not give you the iterator for the last element but one past the last element. 如上所述,end不会为最后一个元素提供迭代器,而是在最后一个元素之后。

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

Why do you want to create pointers of Player ? 为什么要创建Player指针?

Modify the code as follows, 修改代码如下,

In main, 主要的,

vector<Player> allPlayers;
createPlayers(allPlayers);

In createPlayers function: 在createPlayers函数中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM