#include<iostream>
#include <vector>
int main()
{
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(4);
    vec.push_back(4);
    vec.push_back(5);
    for (auto i = vec.begin(); i != vec.end(); ++i)
    {
        if (*i == 4)
        {
            vec.erase(i);
        }
    }
    getchar();
    return 0;
}

如果你这样试图删除为4的元素则达不到效果,因为erase后vec改变迭代器失效,但erase是返回下一个迭代器的

#include<iostream>
#include <vector>
int main()
{
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(4);
    vec.push_back(4);
    vec.push_back(5);
    for (auto i = vec.begin(); i != vec.end();)
    {
        if (*i == 4)
        {
            i = vec.erase(i);//返回被删的下一个迭代器,可以利用这个特性
        }
        else
        {
            i++;
        }
    }
    getchar();
    return 0;
}

 

版权声明:本文为zzyoucan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zzyoucan/p/3674434.html