-1

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++;
    }
}
KnightValor
  • 51
  • 1
  • 5

1 Answers1

1

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.

Community
  • 1
  • 1
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67