“向量擦除迭代器超出范围"在 C++ 中 [英] "Vector erase iterator out of range" in C++

查看:29
本文介绍了“向量擦除迭代器超出范围"在 C++ 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此 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.

有什么问题?毕竟通过这段代码,向量是一个指针向量还是我在 push_back 中传递它们的方式只插入了一个指针副本?

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

推荐答案

.end() 返回迭代器过去一个元素.这就是您收到该错误的原因.您希望迭代器指向最后一个元素.不超过最后一个元素.

.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.

因此尝试将行更改为:

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

并确保正确处理vector为空的情况.

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

或者,您可以使用 .pop_back(),但无论哪种情况,您都需要处理内存泄漏以及评论中提到的问题.

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.

这篇关于“向量擦除迭代器超出范围"在 C++ 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆