You should properly use the return from the function
remove
function. It returns an iterator to the element that follows the last element not removed:
http://www.cplusplus.com/reference/algorithm/remove[
^].
Then you need to use the iterator obtained and the
str.end()
iterator of the original string to pass it to
str.erase
. So, your code will be fixed is your replace your like using
remove
and
erase
with the following line:
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
This is the use of the known
erase-remove idiom explained here:
http://en.wikipedia.org/wiki/Erase-remove_idiom[
^].
See also:
http://en.cppreference.com/w/cpp/algorithm/remove[
^].
However, this is not all. Your problem with the bigger picture — design of your code — is this: with your approach, you would be
jumping from std::string
to the null-terminated representation of strings
and back, which is
utterly inefficient. The null-terminated strings adds CPU usage due to the fact that this presentation "forgets" the length of the string, so the code will have to find it by the terminator over and over each time you use it (for example, initialize another
std::string
with it. This adds a redundant operation of the
time complexity of O(N). Once you got an
std::string
, you should better stay with it. Your function will be more useful if you change its signature in this way:
std::string RemoveSpace(std::string &str)
{
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
See also:
http://en.wikipedia.org/wiki/Time_complexity[
^],
http://en.wikipedia.org/wiki/Big_O_notation[
^],
http://en.wikipedia.org/wiki/Computational_complexity_theory[
^].
[EDIT]
The first comment to the question by Wes Aday actually presented a correct answer (if you remove the text after ';'). I just did not pay attention for it because, when this comment appeared, I was editing this answer in response to an OP's follow-up question
—SA