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;
}
source to share
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.
source to share
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.
source to share
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
.
source to share