C++ STL erase in for loop
程序员文章站
2022-03-23 13:57:44
...
unsafe method: if it is the end, it++ will cause segment fault.
for (vector<int>::iterator it = test1.begin(); it != test1.end(); ) {
if (*it == 3) {
test1.erase(it++);
}
else {
++it;
}
}
safe method:
for (vector<int>::iterator it = test2.begin(); it != test2.end(); ) {
if (*it == 3) {
it = test2.erase(it);
}
else {
++it;
}
}