C++避坑指南-循环内erase

错误写法

循环内直接erase

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
    vector<string> nameList;
    nameList.push_back("小明");
    nameList.push_back("小亮");
    nameList.push_back("小丽");
    nameList.push_back("大壮");

    for(auto it = nameList.begin(); it != nameList.end(); ++it)
    {
        cout << *it << endl;
        if(*it == "小亮")
        {
            nameList.erase(it);
        }
    }
    
    return 0;
}

如上输出结果为:

小明
小亮
大壮
漏掉了处理小丽

错误原因分析

执行erase后, 被erase的迭代器会自动指向下一元素, erase后继续执行迭代器++ 操作导致跳过了一个元素

正确写法

循环代码改写为如下, 首先for循环右边不执行每次迭代器++操作, 

命中要erase的对象情况用it接收返回值,这个返回的迭代器即是erase后的下一元素,所以这里不需要执行迭代器自增了

其他情况执行迭代器自增即可

    for(auto it = nameList.begin(); it != nameList.end(); )
    {
        cout << *it << endl;
        if(*it == "小亮")
        {
            it = nameList.erase(it);
        }
        else
        {
            ++it;
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值