4

I get a file as input and I read the first line like this (quotes mark the begin and end, but are not in the file):

"      1,     2.0,     3.0,     4.0                         "

When I use the remove command like this:

    astring = line;
    cout << endl << "Before trim: " << line << endl;
    remove(astring.begin(), astring.end(), ' ');
    cout << endl << "After trim: " << astring << endl;

I got the output as:

1,2.0,3.0,4.02.0,    3.0,     4.0

I need the output as 1,2.0,3.0,4.0 only. What is the problem here?

1
  • Looks like the tab character. Commented Jul 11, 2011 at 7:01

2 Answers 2

7

std::remove just moves all of the non-removed elements forward in the sequence; you then need to truncate the underlying container, using erase:

s.erase(std::remove(s.begin(), s.end(), ' '), s.end());

This is called the erase-remove idiom. remove cannot truncate the underlying container itself because it doesn't have a reference to the container; it only has iterators to elements in the container.

Sign up to request clarification or add additional context in comments.

2 Comments

I have to say, this is one of the weirdest things about the C++ standard library containers.
@Greg: Yeah, the name remove is not really intuitive. One way to look at it though is that operations on the elements in a container are generally non-member algorithms, but operations on containers themselves are generally member functions on the container classes.
0

James was correct in his answer and it saved me a lot of work. td::remove just moves all of the non-removed elements forward in the sequence; you then need to truncate the underlying container, using erase:

std.erase(std::remove(s.begin(), s.end(), ' '), s.end()); This is called the erase-remove idiom. remove cannot truncate the underlying container itself because it doesn't have a reference to the container; it only has iterators to elements in the container.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.