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?
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 whenstd::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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With