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 给了我以下错误:
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’
我发现了这个问题,但根据 cpp 首选项,这个函数的任何版本都没有接受两个参数。我也发现了这个问题,但是根据cpp首选项(是的,再次),我看到只有一个std::isspace函数重载。
谁是对的?我做错了什么?我该如何解决它?
还有另一个重载std::isspace
,所以你需要指定使用哪一个。一个简单的方法是使用 lambda(或者如果您没有 C++11 支持,则编写自己的单行函数):
std::remove_if(str.begin(), str.end(),
[](char c){
return std::isspace(static_cast<unsigned char>(c));
});
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());
以下解决方案应该可以帮助您解决编译时错误:
str.erase(std::remove_if(str.begin(), str.end(), (int(*) (int)) std::isspace), str.end());
C++ 11 之后,可以使用 lamda 函数(更容易理解),见下文:
string s = " 3/ 2";
auto isSpace = [](const unsigned char c)
{
return std::isspace(c);
};
s.erase(remove_if(s.begin(), s.end(), isSpace), s.end());
输出:
3/2
相关文章:
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 如何在常量计算表达式中获取编译时错误?
- C++根据调用的构造函数强制编译时错误
- 使用 std::iterator_traits<> 时编译时错误不明确
- is_same和variadic模板编译时错误无效转换
- 私有运营商删除会触发 GCC 和 Clang 的编译时错误,但不会在 MSVC 上触发编译时错误
- 运行时与编译时多态性:更好的可读性与编译时错误检查,更重要的是
- 引发编译时错误
- 为什么调用不明确的 ctor 时没有编译时错误?
- 在 sizeof 运算符上强制编译时错误
- 未经授权的私有类成员访问会产生编译时错误而不是运行时错误?
- 将项目插入到std :: map时错误
- 从Mac上的终端编译时C 错误
- 使用MINGW-W64使用-M32选项(32位代码)编译时错误
- C++线程错误 - 带有类参数的编译时错误
- std::remove_if 和 std::isspace - 编译时错误
- 如何使用 std::is_same 生成编译时错误
- Visual Studio 11 使用 std::map 的编译时错误
- std::vector 的 push_back() 导致奇怪的编译时错误消息
- 为什么这个 std::string C++代码不给出编译时错误?