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

Please explain std::logical_not and std::not1 examples of use!

According to the documentation, the former is a “unary class of object functions”, and the latter “constructs a unary object of a function”. So at the end of the day, both create a unary function object, right?

+5
source share
1 answer

Both are functors (class with operator() ), but are slightly different from what they deny:

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

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


Please explain std::logical_not and std::not1 examples of use

Use std::logical_not whenever you can. Use std::not1 whenever your first option is missing. The en.cppreference.com example gives the case when std::not1 is required:

 #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"; } 
+7
source

Source: https://habr.com/ru/post/1245153/


All Articles