KnightValor KnightValor - 1 month ago 9
C++ Question

Deleting Elements of Vector Inside a Loop

I have a vector,

words
, of type:
vector<string>
. I am trying to delete every element of
words
that is not contained in the
vector<string>
called
largest_family
, but can't seem to accomplish this. Any help is appreciated.

vector<string>::iterator it = words.begin();
for (int i = 0; i < words.size(); i++)
{
if (find(largest_family.begin(), largest_family.end(), words[i]) == largest_family.end())
{
words.erase(it);
}
else
{
it++;
}
}

Answer

The right way to perform such task is:

for (vector<string>::const_iterator it = words.begin(); it != words.end();)
{
    if (find(largest_family.begin(), largest_family.end(), *it) == largest_family.end())
    {
        it = words.erase(it);
    }
    else
    {
        ++it;
    }
}

There are many related topics on SO: for example this or this.