vector调用erase 后运行时异常vector iterators incompatible

循环遍历一个vector对象时,当元素值为某些特定值时,从vector中删除该元素后,程序运行时出现error.

解决方法:

http://stackoverflow.com/questions/15042942/vector-iterators-incompatible-while-erase-from-vector

http://stackoverflow.com/questions/10271850/c-stl-vector-iterators-incompatible


std::vector::erase returns an iterator to the next position of the list, and so when you do an erase you should make your iterator equal to the returned value.

The only thing that you have to consider is that the returned iterator could be the end so you should check for that.

What I personally like to do is is after doing in an erase and I get the next iterator position, I go back to the previous position of the returned iterator and than call a continue on the for loop

Example:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> myInt;
    myInt.push_back(1);myInt.push_back(2);myInt.push_back(3);

    for(auto iter = myInt.begin();
        iter != myInt.end();
        ++iter)
    {
        if(*iter == 1)
        {
            iter = myInt.erase(iter);
            if(iter != myInt.begin())
            {
                iter = std::prev(iter);
                continue;
            }
        }

        std::cout << *iter << std::endl;
    }
}

But doing an erase inside of a iterator loop is frowned upon because it invalidates the old iterator and that could cause a lot of issues if you didn't plan for them.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值