你如何使用std :: not1和std :: not2?

use*_*537 6 c++ c++11

目前,如果要否定谓词,则必须使用std::<algorithm>_if_not变量或lambda.但是为了学术,我想知道这是否可行:

std::string s("hello");
std::find_if(s.begin(), s.end(), std::not1(::ispunct));
Run Code Online (Sandbox Code Playgroud)

如果不编写自己的函数对象,如何使这段代码工作?

T.C*_*.C. 9

请记住,将chars 传递给来自C标准库的字符分类函数(以及touppertolower)的正确方法是首先将其转换为unsigned char然后再转换为int.

使用std::refreference_wrapper为此是轻量级的,错误的.使用std::function<bool(int)>std::function<bool(char)>更重量级,也是错误的.在所有这些情况下char,字符串中的字符串直接转换为int,这不是正确的方法.

如果你坚持不使用lambda,那么

std::find_if(s.begin(), s.end(), std::not1(std::function<bool(unsigned char)>(::ispunct)));
Run Code Online (Sandbox Code Playgroud)

是一种正确的方法.除此以外

std::find_if(s.begin(), s.end(), [](unsigned char c) { return !ispunct(c); });
Run Code Online (Sandbox Code Playgroud)

更容易理解 - 更短.