在迭代嵌套向量时删除元素

时间:2017-05-24 04:59:20

标签: c++

我想知道如何在保留迭代器的同时擦除向量的元素?这里我循环遍历int类型向量的向量:

vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = vvi.begin(); row != vvi.end(); row++) {
    for (col = row->begin(); col != row->end(); col++) {
        if(*col==55)
        {
           //  col=row.erase(col); ?
        }

    }
}

1 个答案:

答案 0 :(得分:0)

在你的代码中,如果有多个元素等于55,则会有多次擦除向量元素,这将花费很多开销来移动元素。 更好的解决方案是按照erase-remove idiom将所有限定元素移动到向量的末尾,然后一次擦除它们。 例如:

vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = vvi.begin(); row != vvi.end(); row++) {
     row->erase( std::remove( row->begin(), row->end(), 55), row->end());
}

std :: remove会将所有等于55的元素移动到向量的末尾并返回它们的头部的迭代器。 row-&gt; erase(iterator1,iterator2)将擦除2个迭代器之间的所有元素。

你不再需要关心迭代器了。