-5

Consider this following program:

#include <iostream>
#include <string>
#include <algorithm>    // std::remove

int main ()
{
  std::string str ("This is   an   example sentence blah");
  std::remove(str.begin(), str.end(), '\t');
  std::cout << str ;
  return 0;

}

There is a tab between the words (is,an) and (an,example), others are spaces.

I expected the output to be :

This isanexample sentence blah

Instead, i am getting the following output:

This isanexample sentence blahah

Is there a buffer overrun somewhere for the extra 'ah'?

More: I noticed after several runs that, the number of trailing letters at the end is proportional to number of tabs being removed. In this case there are 2 tabs in the string, hence 2 extra trailing characters. I can take care of it by using erase, but why does it happen? I am not sure if it's a design flaw or am i missing something?

SeasonalShot
  • 2,357
  • 3
  • 31
  • 49

1 Answers1

2

Yes, you are missing the fact that std::remove, as pointed out in any documentation, doesn't actually remove elements from the containers.

When an element to be removed is found, the elements past it are shifted toward the begin of the container (through move assignment operator=(T&&)) and an iterator to the new end of the container is returned, but the container itself is unaffected.

So to actually remove them from a container you should do:

auto it = std::remove(...);
container.erase(it, container.end());
Jack
  • 131,802
  • 30
  • 241
  • 343