Compare to remove_if in c++ does not accept char

Asked

Viewed 32 times

0

Hello, I’m trying to use a

remove_if

in c++ but when it gets to the input part I can’t determine for it to detect if the string I’m pointing has a char. Follows my code:

temp.erase(remove_if(temp.begin(), temp.end(), "("), temp.end());

temp is a string. wanted it to detect "(" but I’m not even able to compile that way. I saw some people saying that it is necessary to create a function for this, but I do not know how I should return such a function. Someone could help?

1 answer

2


The remove_if takes 3 parameters, the start and end iterators and a function that takes a parameter and returns a bool. In this case you can pass the function using its name as if it were a variable.

Follow the code below:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool isParenthesis (char c) {
  return c == '(';
}

int main () {
  string temp = "123(456";

  temp.erase(remove_if(temp.begin(), temp.end(), isParenthesis));

  cout << temp;
  cout << endl;
  return 0;
}

You can also see an example in documentation.

  • I can do that for more than one char?

  • 1

    You want to compare with more than one char in isParenthesis? You can use the || thus return c == '(' || c == ')';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.