How does the C++ code `x.erase(std::remove(x.begin(), x.end(), ' '), x.end())` work?

Viewed 417

The thing is I usually would use a for loop to handle this kind of thing but this method seems to be much more efficient. The documentation on cplusplus was a bit hard to comprehend for me.

std::string no_space(std::string x)
{
    x.erase(std::remove(x.begin(), x.end(), ' '), x.end());
    return x;
}
3 Answers

Let's break it down some

std::remove(x.begin(), x.end(), ' ')

This goes through all the elements of x, and overwrites any spaces with the next non-space. It returns the position one beyond the last non-space character. Importantly it does not change the size of x. Imagine the return value is assigned to a std::string::iterator it. From it to the end of x the elements are in a valid but unspecified state.

x.erase(it, x.end());

This removes elements from x, starting with the position returned by remove. This eliminates all the "valid but unspecified state" values from the end of x, which were left behind by remove.

Related