remove_if bugged?

1
2
3
4
5
6
7
8
int main()
{
	string str = "Archer Level 1";
	remove_if(str.begin(), str.end(), isspace);
	cout << str << endl;
	cin.ignore();
	return 0;
}


ArcherLevel1 1
Go read the manual.

Last edited on
Try:

 
    str.erase(std::remove_if(str.begin(), str.end(), isspace), str.end());

The problem is that remove_if doesn't have access to the container so it can't remove elements from it. Instead it just keeps the elements that should be removed at the end and returns the position where that is so that you can remove them yourself.

There has been a proposal to add erase_if which just takes a container and a predicate as argument and automatically removes the elements. Unfortunately it hasn't been accepted yet, but we will probably have something like this in the standard library in a few years time.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <experimental/string>

int main()
{
	std::string str = "Archer Level 1";
	std::experimental::erase_if(str, [](char c){ return std::isspace(c); });
	std::cout << str; // prints "ArcherLevel1"
}

https://en.cppreference.com/w/cpp/experimental/basic_string/erase_if
Last edited on
Thanks guys i understood!
Topic archived. No new replies allowed.