c++ - 如何从 vector 中删除元素并更新迭代器?

标签 c++ vector

我正在尝试从特定索引处的 vector 中删除一个对象。 vector 迭代器在整个程序中跟踪索引。在下面的代码中,第一个 IF 语句完美运行。但是,如果迭代器指向最后一个元素以外的任何地方,我会从 vector 中删除该元素,然后递增迭代器。程序崩溃并提示“迭代器不可递增”。

我运行了几次调试器,一切看起来都是正确的,所以我看不出我遗漏了什么?

vector<Card> myVector; //container to hold collection of cards.
vector<Card>::iterator myVectorIterator; //points to each "card" in the collection.

Card Collection::remove() 
{
    if (myVectorIterator== myVector.end()-1) { //at the last card
        //erase the "current" card
        myVector.erase(myVectorIterator); 
        //update to the first card.
        myVectorIterator= myVector.begin();
       } 
    else
    {   

        myVector.erase(myVectorIterator); 

        //crashes here!
        myVectorIterator++;
    }

return *myVectorIterator;

最佳答案

erase 使迭代器无效,因此以后不能使用它。但它有助于将迭代器返回到删除元素之后的元素:

myVectorIterator = myVector.erase(myVectorIterator);

关于c++ - 如何从 vector 中删除元素并更新迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24739599/

相关文章:

c++ - 当 vector 存储在 RAM 中时,变量到底存储在哪里?

c++ - 为什么此代码会出现 'expression syntax' 错误?

c++ - 如何检查所需的输入数量是否正确

c++ - 调整类中二维 vector 的大小

用不均匀向量列表中的正值替换正表值

c++ - 继承包含另一个派生类的 C++ 类

c++ - 使用在外部类内部声明的数据类型

c++ - 基于不同字段的对象 vector 的排序函数

C++ std::vector 带有指向模板类的指针

r - 按名称添加两个向量