g ++ chaîne d'erreur remove_if
-
27-10-2019 - |
Question
Voici le 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());
}
Lors de la compilation dans VS 2010, il fonctionne parfaitement bien. G ++ compilé avec il est dit:
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>)'
La solution
Ajouter ::
au début de isspace
, ispunct
et isdigit
, car ils ont le compilateur que la surcharge ne peut pas décider sur lequel utiliser:
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());
Autres conseils
Ajouter #include <cctype>
(et dire std::isspace
etc. si vous n'êtes pas abusing namespace std;
).
Il faut toujours inclure tous les en-têtes que vous avez besoin, et ne pas se fier sur les inclusions imbriquées cachées.
Vous pouvez également désambiguïser la surcharge de l'autre dans <locale>
. Pour ce faire, en ajoutant un casting explicite:
word.erase(std::remove_if(word.begin(), word.end(),
static_cast<int(&)(int)>(std::isspace)),
word.end());
Pour moi, il compile en utilisant g ++ si je fais une des opérations suivantes:
- supprimer
using namespace std;
et le changementstring
àstd::string
; ou - changement
isspace
à::isspace
(etc.).
Chacune de ces causera isspace
(etc.) à prendre de l'espace de noms principal, au lieu d'être interprété en ce sens peut-être std::isspace
(etc.).
Le problème est que std :: isspace (int) prend un int comme paramètre, mais une chaîne est composée de charbon. Donc, vous devez écrire votre propre fonction:
bool isspace (char c) {return c == ' « ; }
Le même pour les deux autres fonctions.