Domanda

Ecco il codice:

#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());
}

Se compilato in VS 2010, funziona perfettamente. Compilato con G ++ dice:

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>)'
È stato utile?

Soluzione

Aggiungere :: all'inizio di isspace, ispunct e isdigit, poiché hanno sovraccarico che il compilatore non può decidere su quale usare:

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());

Altri suggerimenti

Aggiungere #include <cctype> (e dire std::isspace ecc. Se non lo sei abusing namespace std;).

Includi sempre tutte le intestazioni di cui hai bisogno e non fare affidamento su inclusioni nidificate nascoste.

Potrebbe anche essere detestato il sovraccarico dall'altro in <locale>. Fallo aggiungendo un cast esplicito:

word.erase(std::remove_if(word.begin(), word.end(),
                          static_cast<int(&)(int)>(std::isspace)),
           word.end());

Per me si compila usando G ++ se faccio uno dei seguenti:

  • rimuovere using namespace std; e cambiare string a std::string; o
  • modificare isspace a ::isspace (eccetera.).

Ognuno di questi causerà isspace (ecc.) Da prendere dallo spazio dei nomi principali, invece di essere interpretato come possibile significato std::isspace (eccetera.).

Il problema è che STD :: ISSPACE (INT) prende un INT come parametro ma una stringa è composta da char. Quindi devi scrivere la tua funzione come:

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

Lo stesso vale per le altre due funzioni.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top