std::logical_not 和 std::not1 之间的区别

Difference between std::logical_not and std::not1?

本文关键字:std 之间 区别 not1 not logical      更新时间:2023-10-16

请举例说明何时使用std::logical_not,何时使用std::not1

根据文档,前者是"一元函数对象

类",而后者是"构造一元函数对象"。所以在一天结束时,两者都构造了一个一元函数对象,不是吗?

两者都是函子(一个带有operator()的类),但在它们否定的内容上略有不同:

  • std::logical_not<T>::operator()返回T::operator!() .从语义上讲,它将T视为一个值并否定它。
  • std::not1<T>::operator()返回!(T::operator()(T::argument_type&)) .在语义上,它将T视为谓词并对其进行否定。

std::not1<T> 是针对更复杂用例的std::logical_not的概括。


请举例说明何时使用std::logical_not以及何时使用std::not1

尽可能使用std::logical_not。每当第一个选项出来时,请使用std::not1。en.cppreference.com 上的示例给出了需要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";
}