g ++ string remove_if ошибка
-
27-10-2019 - |
Вопрос
Вот код:
#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());
}
При составлении в VS 2010 это работает совершенно нормально. Скомпилируется с G ++, он говорит:
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>)'
Решение
Добавлять ::
к началу isspace
, ispunct
а также isdigit
, поскольку у них есть перегрузки, которые компилятор не может решить, что использовать:
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());
Другие советы
Добавлять #include <cctype>
(и скажи std::isspace
и т. д., если вы не abusing namespace std;
).
Всегда включайте все заголовки, которые вам нужны, и не полагайтесь на скрытые вложенные включения.
Вам также может придется уволить перегрузку от другого в <locale>
. Анкет Сделайте это, добавив явный актерский состав:
word.erase(std::remove_if(word.begin(), word.end(),
static_cast<int(&)(int)>(std::isspace)),
word.end());
Для меня он компилирует с использованием G ++, если я сделаю любое из следующего:
- удалять
using namespace std;
и изменитьstring
кstd::string
; или же - сдача
isspace
к::isspace
(так далее.).
Любой из них вызовет isspace
(и т. д.) быть взятым из основного пространства имен, вместо того, чтобы интерпретировать как, возможно, смысл std::isspace
(так далее.).
Проблема в том, что std :: iSspace (int) принимает Int в качестве параметра, но строка состоит из Char. Итак, вы должны написать свою собственную функцию как:
Bool Isspace (char c) {return c == ''; }
То же самое относится и к двум другим функциям.