std :: remove_if和std :: isspace - 编译时错误 [英] std::remove_if and std::isspace - compile-time error
问题描述
我有以下代码:
#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我的以下错误:
MSVC-11.0 compiles this code without any error, but gcc 4.7.2 gives me the following errors:
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’
href =http://stackoverflow.com/questions/15985612/remove-if-throw-error-when-trying-to-remove-white-space>这关于它的问题,但根据< a href =http://en.cppreference.com/w/cpp/string/byte/isspace> cppreference ,没有任何版本的此函数接受两个参数。我也发现了这个问题,但是根据cppreference(是的,再次)我看到只有一个std :: isspace函数重载。
I found this question about it, but according to the cppreference, there isn't any version of this function that takes two arguments. I found this question too, but according to the cppreference (yep, again) I see that there's only one std::isspace function overload.
谁是对的?我做错了什么?如何解决?
Who's right? What am I doing wrong? How can I fix it?
推荐答案
有 std :: isspace
的另一个重载,因此您需要指定使用哪一个。一个简单的方法是使用lambda(或者如果你没有C ++ 11支持,写一个自己的一行函数):
There is another overload of std::isspace
, so you need to specify which one to use. An easy way is to use a lambda (or write your own one-line function if you don't have C++11 support):
std::remove_if(str.begin(), str.end(),
[](char c){
return std::isspace(static_cast<unsigned char>(c));
});
这篇关于std :: remove_if和std :: isspace - 编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!