从Vector Inside Loop中删除元素

时间:2016-10-21 06:05:04

标签: c++ vector

我有一个类型为words_in_family的向量vector<vector<string>>。我试图删除words_in_family中不等于字符串向量largest_family的每个元素,但是遇到问题并且不确定原因。任何帮助表示赞赏。

for (int i = words_in_family.size() - 1; i >= 0; i--)
{
    if (words_in_family[i] != largest_family)
    {
        words_in_family.erase(words_in_family[i]);
    }
}

3 个答案:

答案 0 :(得分:1)

erase方法没有取值。而是使用迭代器作为erase方法的参数:

vector<vector<string>>::iterator it = words_in_family.begin();
for (int i = words_in_family.size() - 1; i >= 0; i--)
{
    if (words_in_family[i] != largest_family)
    {
        words_in_family.erase(it+i);
    }
}
  

迭代器擦除(迭代器位置);   迭代器擦除(迭代器优先,迭代器最后);

请注意,std :: vector的迭代器是随机访问迭代器,因此您可以添加/减去整数值以获取其他有效迭代器。

答案 1 :(得分:1)

C ++ std::vector擦除一个元素,在你的情况下:

删除值等于words_in_family的向量(largest_family)中的元素:

std::vector<std::vector<std::string>>::iterator Itr;
for(Itr = Words_in_family.begin(); Itr != Words_in_family.end();)
{
    if(*Itr == largest_family)
    {
        Itr = Words_in_family.erase(Itr);
    }
    else
    {
        Itr++;
    }
}

答案 2 :(得分:0)

words_in_family.erase(words_in_family.begin()+i, words_in_family.begin()+i+1);

erase将迭代器作为参数