Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ string remove_if error

Here's the code:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string word="";
    getline(cin,word);
    word.erase(remove_if(word.begin(), word.end(), isspace), word.end()); 
    word.erase(remove_if(word.begin(), word.end(), ispunct), word.end()); 
    word.erase(remove_if(word.begin(), word.end(), isdigit), word.end());
}

When compiled in VS 2010, it works perfectly fine. Compiled with G++ it says:

hw4pr3.cpp: In function `int main()':
hw4pr3.cpp:20: error: no matching function for call to `remove_if(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unknown type>)'
hw4pr3.cpp:21: error: no matching function for call to `remove_if(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unknown type>)'
hw4pr3.cpp:22: error: no matching function for call to `remove_if(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unknown type>)'
like image 223
Richard Avatar asked Dec 03 '11 01:12

Richard


2 Answers

Add :: to the beginning of isspace, ispunct and isdigit, since they have overloads that the compiler can't decide on which to use:

word.erase(remove_if(word.begin(), word.end(), ::isspace), word.end()); 
word.erase(remove_if(word.begin(), word.end(), ::ispunct), word.end()); 
word.erase(remove_if(word.begin(), word.end(), ::isdigit), word.end());
like image 84
AusCBloke Avatar answered Oct 02 '22 20:10

AusCBloke


The problem is that std::isspace(int) takes an int as a parameter but a string is composed of char. So you have to write your own function as:

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

The same applies to the other two functions.

like image 43
memecs Avatar answered Oct 02 '22 18:10

memecs