迭代器erase元素注意事项

// del_iter_test.cpp : 定义控制台应用程序的入口点。
//

//测试迭代器删除
#include "stdafx.h"
#include <vector>
#include <iostream>

using namespace std;

vector<int> vec;

void init() {
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);
    vec.push_back(6);

}

void test() {

    for (auto it = vec.begin(); it != vec.end(); it++ )
    {
        if ((*it) == 2) {
            it = vec.erase(it); // 
        }
    }
}

void printvec() {
    for (auto& it :vec)
    {
        cout << "i =" << it << endl;
    }
}


int main()
{
    init();
    test();
    printvec();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/codeproject/p/12970995.html
今日推荐