KnightValor KnightValor - 1 month ago 9
C++ Question

Delete Elements from Vector Inside Loop

I have a vector,

words_in_family
, of type:
vector<vector<string>>
. I am trying to delete every element of
words_in_family
that is not equal to the string vector
largest_family
, but am having issues and am unsure of why. Any help is appreciated.

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]);
}
}

Answer

erase method doesn't take value. Instead use iterator as parameter for erase method:

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);
    }
}

iterator erase (iterator position); iterator erase (iterator first, iterator last);

Note that the iterators for std::vector are random access iterators so you can add/subtract integral values to get other valid iterators.