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

The thing is, I usually use a for loop to handle this sort of thing, but this method seems to be much more efficient. The documentation on cplusplus was a little hard to understand for me.

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

      

+3


source to share


3 answers


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

moves elements to the end of the line, and the function std::erase

actually removes the elements that were moved to the end of the line. You can also read about it in the documentation enter link here



There is an example like you.

+3


source


std::remove

moves all spaces to the end of the string and returns the iterator to the first space. Then it string::erase

removes from that first space to the end of the line.



This is a simplified description, as commenters have duly pointed out, make sure you read the documentation for these functions.

+1


source


Let's break some

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

      

This goes through all the elements x

and overwrites any whitespace with the next non-space. It returns the position outside the last nonspatial character. It's important to note that it doesn't change size

x

. Imagine the return value is being assigned std::string::iterator it

. From it

to the end, the x

items are in a valid but unspecified state.

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

      

This removes elements from x

, starting at the position returned remove

. This removes any valid-but-unspecified state values ​​from the end x

that are left behind remove

.

0


source







All Articles