Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

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

According to documentation, the former is a "unary function object class" while the latter "constructs a unary function object". So at the end of the day both construct a unary function object, don't they?

like image 575
steffen Avatar asked Mar 16 '16 10:03

steffen


1 Answers

Both are functors (a class with an operator()), but differ slightly on what they negate:

  • std::logical_not<T>::operator() returnsT::operator!(). Semantically, it sees T as a value and negates it.
  • std::not1<T>::operator() returns !(T::operator()(T::argument_type&)). Semantically, it sees T as a predicate and negates it.

std::not1<T> is a generalization of std::logical_not for more complex use case.


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

Use std::logical_not whenever you can. Use std::not1 whenever your first option is out. The example on en.cppreference.com gives a case where std::not1 is necessary:

#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";
}
like image 145
YSC Avatar answered Nov 01 '22 23:11

YSC