你如何使用std :: not1和std :: not2? [英] How do you use std::not1 and std::not2?

查看:170
本文介绍了你如何使用std :: not1和std :: not2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  std :: string s(hello); 
std :: find_if(s.begin(),s.end(),std :: not1(:: ispunct));

没有写我自己的函数对象,如何使这个代码工作?

$ b $请记住,将 char 的正确方法传递到字符分类函数(以及<$>

来自C标准库的c $ c> toupper 和 tolower 是将它首先转换为 unsigned char ,然后到 int



使用 std :: ref reference_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))); 

是一种正确的方法。否则

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

更容易理解 - 更短。


Currently if you want to negate a predicate, you have to use a std::<algorithm>_if_not variant or a lambda. But for the sake of academics I want to know if this is possible:

std::string s("hello");
std::find_if(s.begin(), s.end(), std::not1(::ispunct));

Without writing my own function object, how to make this code work?

解决方案

Remember that the correct way to pass chars to the character classification functions (along with toupper and tolower) that came from the C standard library is to convert it first to unsigned char and then to int.

Using std::ref and a reference_wrapper for this is lightweight, and wrong. Using std::function<bool(int)> or std::function<bool(char)> are more heavyweight, and also wrong. In all those cases the char in the string is directly converted to int, which is not the right way to do it.

If you insist on not using a lambda, then

std::find_if(s.begin(), s.end(), std::not1(std::function<bool(unsigned char)>(::ispunct)));

is one right way to do it. Otherwise

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

is easier to understand - and shorter.

这篇关于你如何使用std :: not1和std :: not2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆