Search code examples
c++algorithmremove-if

Trouble with remove_if (it stops removing after a few removals)


The code below wants to take a string and output only lowercase letters from the English alphabet.

string simplifyString(string word)
{
    word.erase(remove_if(word.begin(), word.end(), [](char letter){return !isalpha(letter);}));
    transform(word.begin(), word.end(), word.begin(), tolower);
    return word;
}

int main()
{
    string s = "a.b.c.d.e.f.g.h.";
    cout << simplifyString(s) << endl;;
    return 0;
}

The output is: abcdefgh.f.g.h.

So the code works and then stops working. What the heck is going on?


Solution

  • word.erase(remove_if(...));
    

    That's close but not quite right. That only removes the first element set aside by remove_if. You want to remove the entire range:

    word.erase(remove_if(...), word.end());