欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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