C++ std::logical_not和std::not1之间的区别?
请举例说明何时使用C++ std::logical_not和std::not1之间的区别?,c++,std,C++,Std,请举例说明何时使用std::logical\u not以及何时使用std::not1 根据文献记载,前者是“一元函数对象类”,而后者“构造一元函数对象”。因此,在一天结束时,它们都构造了一元函数对象,不是吗?它们都是函子(一个带有操作符()的类),但在否定什么方面略有不同: std::logical\u not::operator()返回T::operator!()。在语义上,它将T视为一个值,并将其取反 std::not1::operator()返回!(T::operator()(T::ar
std::logical\u not
以及何时使用std::not1
根据文献记载,前者是“一元函数对象类”,而后者“构造一元函数对象”。因此,在一天结束时,它们都构造了一元函数对象,不是吗?它们都是函子(一个带有操作符()
的类),但在否定什么方面略有不同:
返回std::logical\u not::operator()
。在语义上,它将T::operator!()
视为一个值,并将其取反T
返回std::not1::operator()
。在语义上,它将!(T::operator()(T::argument_type&)
视为谓词,并对其进行否定T
std::not1
是std::logical\u not
的泛化,用于更复杂的用例
请举例说明何时使用
std::logical_not
以及何时使用std::not1
尽可能使用std::logical\u not
。当您的第一个选项不可用时,请使用std::not1
。上的示例给出了需要std::not1
的情况:
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <iostream>
#include <vector>
struct LessThan7 : std::unary_function<int, bool>
{
bool operator()(int i) const { return i < 7; }
};
int main()
{
std::vector<int> v(10);
std::iota(begin(v), end(v), 0);
std::cout << std::count_if(begin(v), end(v), std::not1(LessThan7())) << "\n";
//same as above, but use a lambda function
std::function<int(int)> less_than_9 = [](int x){ return x < 9; };
std::cout << std::count_if(begin(v), end(v), std::not1(less_than_9)) << "\n";
}
#包括
#包括
#包括
#包括
#包括
#包括
struct LessThan7:std::一元函数
{
布尔运算符()(int i)常量{return i<7;}
};
int main()
{
std::向量v(10);
标准::物联网(开始(v)、结束(v)、0);
std::cout注意:1元函数
已被弃用(lambda更好)。问题是,lambda没有参数类型
成员,std::not1
需要它。