std::logical_not 和 std::not1 的区别?

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

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

根据文档,前者是 "unary function object class" 而后者是 "constructs a unary function object"。所以最终两者都构造了一个一元函数对象,不是吗?

两者都是函子(一个 class 和一个 operator()),但它们取反的内容略有不同:

  • std::logical_not<T>::operator()returnsT::operator!()。从语义上讲,它将 T 视为一个值并将其取反。
  • std::not1<T>::operator()returns!(T::operator()(T::argument_type&))。从语义上讲,它将 T 视为谓词并否定它。

std::not1<T>std::logical_not 的概括,适用于更复杂的用例。


Please explain with examples when to use std::logical_not and when std::not1

尽可能使用 std::logical_not。每当您的第一个选项不可用时,请使用 std::not1en.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";
}