菜鸟笔记
提升您的技术认知

vector中erase的用法-ag真人游戏

erase的函数原型有两种形式:

iterator erase(iterator position);

iterator erase(iterator first, iterator last); // 返回指向下一个元素的迭代器

 

错误示范:

std::vector vec;
for (int i = 0; i < 10;   i)
{
    vec.push_back(i);  
}
for (std::vector::iterator it = vec.begin(); it != vec.end();   it)
{
    if (1 == *it) {
        vec.erase(it);
    }    
}

正确的使用方式:

std::vector vec;
    for (int i = 0; i < 10;   i)
    {
        vec.push_back(i);
    }
    vec.push_back(1);
    vec.push_back(1);
    vec.push_back(1);
    vec.push_back(1);
    for (auto it = vec.begin(); it != vec.end();)
    {
        if (1 == *it) {
            it = vec.erase(it);
        }
        else {
              it;
        }
    }

 

网站地图