-2

Hello I am using visual studio 2012, and when I use this code

remove(str.begin(), str.end(), ' ')

with:

str="hel lo world"

I get the output: helloworldld

Yes there is additional ld. When I try this on hackerrank it gives no problem. Why different environment gives no problem with the statement but VS does?

  • 3
    This is the expected behaviour. Please read the documentation. – IMil Oct 11 '18 at 03:05
  • You all right but I do not understand is why it does not work on my VS but works on a different environment such as hackerrank? – user10487297 Oct 11 '18 at 10:25
  • @user10487297 You aren't using the algorithm correctly. The trailing elements are unspecified, they can have different values for any reason, including changing platform. – François Andrieux Oct 11 '18 at 18:15

3 Answers3

0

Please take a look at the docs for std::remove([...]):

2 Effects: Eliminates all the elements referred to by iterator i in the range [first, last) for which the following corresponding conditions hold: *i == value, pred(*i) != false.
3 Returns: The end of the resulting range.
[...]
6 [ Note: Each element in the range [ret, last), where ret is the returned value, has a valid but unspecified state, because the algorithms can eliminate elements by moving from elements that were originally in that range. — end note ]

The physical size of the range isn't changed, but all elements which aren't removed are now in the range [first, return).

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
0

According to the documentation (http://www.cplusplus.com/reference/algorithm/remove/), "The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the elements that compare equal to val by the next element that does not, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element".

The right way to do it can be found here: How to remove certain characters from a string in C++?

Note that myvector.erase (myvector.begin()+a,myvector.begin()+b); removes indexes a,a+1,a+2,...,b-1 from myvector (a <= b). On the other hand, myvector.remove (myvector.begin(),myvector.end(), 'c'); returns the new end iterator of the "correct" myvector without occurrences of 'c'. So, you can assign the returned iterator to an iterator variable like the solution in the link above, then the old start iterator through that iterator variable will be your new "correct" vector.

won ton
  • 3
  • 1
  • 3
0

You failed to use the return value to resize the string properly:

str.resize(remove(str.begin(), str.end(), ' ') - str.begin());
Chris Dodd
  • 119,907
  • 13
  • 134
  • 226