我有以下代码:
#include <algorithm>
#include <cctype>
#include <string>
int main()
{
std::string str;
str.erase(std::remove_if(str.begin(), str.end(), std::isspace), str.end());
}MSVC-11.0编译此代码时没有任何错误,但是gcc 4.7.2给出了以下错误:
main.cpp: In function ‘int main()’:
main.cpp:8:66: error: no matching function for call to ‘remove_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)’
main.cpp:8:66: note: candidate is:
In file included from /usr/include/c++/4.7/algorithm:63:0,
from main.cpp:1:
/usr/include/c++/4.7/bits/stl_algo.h:1160:5: note: template<class _FIter, class _Predicate> _FIter std::remove_if(_FIter, _FIter, _Predicate)
/usr/include/c++/4.7/bits/stl_algo.h:1160:5: note: template argument deduction/substitution failed:
main.cpp:8:66: note: couldn't deduce template parameter ‘_Predicate’我发现了这关于它的问题,但是根据优先选择,没有任何版本的函数使用两个参数。我也发现了这问题,但是根据偏好(是的,再次),我看到只有一个std::isspace函数重载。
谁是对的?我做错了什么?我怎么才能修好它?
发布于 2014-02-05 13:25:14
有std::isspace,所以您需要指定使用哪一个。一种简单的方法是使用lambda (如果不支持C++11,则编写您自己的一行函数):
std::remove_if(str.begin(), str.end(),
[](char c){
return std::isspace(static_cast<unsigned char>(c));
});发布于 2014-02-05 13:25:36
std::isspace是一个重载函数,尽管这两个重载位于不同的标题中。还请注意,您的代码可能会引入未定义的行为,因为只有范围0..UCHAR_MAX中的值可以传递给std::isspace,而char可能被签名。
以下是一个解决方案:
std::string str;
auto f = [](unsigned char const c) { return std::isspace(c); };
str.erase(std::remove_if(str.begin(), str.end(), f), str.end());发布于 2020-10-16 20:28:32
以下解决方案将帮助您避免编译时错误:
str.erase(std::remove_if(str.begin(), str.end(), (int(*) (int)) std::isspace), str.end());https://stackoverflow.com/questions/21578544
复制相似问题