我有以下代码:
#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’
I found this https://stackoverflow.com/questions/15985612/remove-if-throw-error-when-trying-to-remove-white-space对此有疑问,但根据参考参数 http://en.cppreference.com/w/cpp/string/byte/isspace,此函数没有任何版本需要两个参数。我发现this https://stackoverflow.com/questions/4537930/removing-a-character-from-a-string问题也是,但根据 cppreference (是的,再次)我看到只有一个 std::isspace 函数重载。
谁是对的?我究竟做错了什么?我该如何修复它?
有另一个超载std::isspace http://en.cppreference.com/w/cpp/locale/isspace,因此您需要指定使用哪一个。一种简单的方法是使用 lambda(或者如果没有 C++11 支持,则编写自己的单行函数):
std::remove_if(str.begin(), str.end(),
[](char c){
return std::isspace(static_cast<unsigned char>(c));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)