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