vector中erase的用法

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

iterator erase(iterator position);

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

 

错误示范:

std::vector<int> vec;
for (int i = 0; i < 10; ++i)
{
    vec.push_back(i);  
}

for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
{
    if (1 == *it) {
        vec.erase(it);
    }    
}

正确的使用方式:

std::vector<int> 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;
        }
    }

 

posted @ 2019-02-01 15:19  c&z  阅读(26601)  评论(4编辑  收藏  举报