以下是查找字符串是否仅包含数字的代码:
#include <iostream> //see below
#include <string>
#include <cctype>
#include <algorithm>
int main() {
std::string s("123");
std::all_of(s.begin(), s.end(), std::isdigit); //error!
}
Run Code Online (Sandbox Code Playgroud)
但代码无法编译,出现以下错误:
error: no matching function for call to 'all_of'
note: candidate template ignored: couldn't infer template argument '_Predicate'
all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
Run Code Online (Sandbox Code Playgroud)
当我替换std::isdigit为时isdigit,代码编译时没有错误。
error: no matching function for call to 'all_of'
note: candidate template ignored: couldn't infer template argument '_Predicate'
all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
Run Code Online (Sandbox Code Playgroud)
isdigit那么和之间有什么区别呢std::isdigit?我知道它isdigit是从 C header 继承的ctype.h,并且std::isdigit是 C++ header 中定义的包装器cctype,所以本质上它们应该是相同的。我有什么错吗?
我在 Appleclang和 linux上尝试了上述方法g++,并得到了类似的错误。
更令人困惑的是,当我删除#include <iostream>Apple 上的行时clang,代码再次编译:
#include <iostream> //see below
#include <string>
#include <cctype>
#include <algorithm>
int main() {
std::string s("123");
std::all_of(s.begin(), s.end(), isdigit); //OK
}
Run Code Online (Sandbox Code Playgroud)
但删除#include <iostream>对 不起作用gcc。
由于两者clang都gcc生成了相同的错误,因此它不太可能是编译器的错误。我在这里有什么问题吗?
在 C++ 中,不允许获取大多数标准库函数的地址:
https://en.cppreference.com/w/cpp/language/extending_std#Addressing_restriction
如果 C++ 程序显式或隐式尝试形成指针、引用(对于自由函数和静态成员函数)或指向成员的指针(对于非静态成员函数),则该程序的行为是未指定的(可能是格式错误的)标准库函数或标准库函数模板的实例,除非指定为可寻址函数
std::isdigit()不是可寻址的标准库函数,因此不能直接将其用作算法谓词。
首先说的是,即使您可以std::isdigit()直接作为谓词传递,这样做也会带来未定义行为的风险:
https://en.cppreference.com/w/cpp/string/byte/isdigit
与 中的所有其他函数一样,如果参数的值既不能表示为也不等于 ,则
<cctype>的行为是未定义的。要与普通s (或s)安全地使用这些函数,参数应首先转换为:std::isdigitunsigned charEOFcharsigned charunsigned charRun Code Online (Sandbox Code Playgroud)bool my_isdigit(char ch) { return std::isdigit(static_cast<unsigned char>(ch)); }
char同样,当迭代器的值类型为或时,它们不应该直接与标准算法一起使用signed char。相反,将值转换为unsigned char第一个:Run Code Online (Sandbox Code Playgroud)int count_digits(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isdigit) // wrong // [](int c){ return std::isdigit(c); } // wrong // [](char c){ return std::isdigit(c); } // wrong [](unsigned char c){ return std::isdigit(c); } // correct ); }
因此,由于您需要将每个值相互转换char,unsigned char因此您应该在std::isdigit()用作 谓词的 lambda 内部调用std::all_of(),例如:
std::all_of(s.begin(), s.end(),
[](unsigned char ch){ return std::isdigit(ch); }
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
589 次 |
| 最近记录: |