g++ string remove_if error

g++ string remove_if error

本文关键字:if error remove string g++      更新时间:2023-10-16

代码:

#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, ispunctisdigit的开头,因为它们有过载,编译器无法决定使用哪个:

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>(如果您不是abusing namespace std;,则说std::isspace等)。

总是包含你需要的所有头,不要依赖于隐藏的嵌套包含。

您可能还必须消除<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){返回c == ' ';}

其他两个函数也是如此