How to use std :: remove'd line in C ++?

Assume the following:

string s("!Hello!'");

My goal is to get in the variable s only the string "Hello", IOW I want to remove the exclamation points.

I tried the following:

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

When I exit the resulting string s, I get:

Helloo!

"!" characters were deleted, but the end of the line was not moved.

I read that I need to return an iterator from the return value of std :: remove, but I'm new to C ++ and not succeeding in it.

I expect something like char :: iterator to be valid, but it seems not ... so

char::iterator new_end;
new_end = std::remove ( s.begin(), s.end(), '!' );
cout << new_end ;

doesn't do that.

Any help / pointers would be appreciated!

+3
source share
3 answers

std::removeworks on iterators, not containers. Therefore, it cannot resize the container.

erase-remove idiom:

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

remove - , , . erase, , , remove.

+9

. C. "end" , , ( '*')

, , . , , .

template<typename Collection, typename Element>
void remove_elements(Collection& c, const Element& e) {
    c.erase(std::remove(c.begin(), c.end(), e), c.end());
};

:

remove_elements(s, '!');
+2

While others have shown you a solution, invite you to check Scott Meyer's β€œ Understanding Why Remove Doesn’t Really Delete Anything ” (somewhere in the middle of the page - the whole page makes an interesting read, BTW).

0
source

All Articles