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

时间:2016-03-16 10:42:55

标签: c++ std

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

根据文档,前者是“一元函数对象类”,而后者“构造一元函数对象”。所以在一天结束时都构造了一个一元函数对象,不是吗?

1 个答案:

答案 0 :(得分:7)

两者都是仿函数(一个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::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";
}
相关问题