请用例子说明何时使用
根据文档,前者是“一元函数对象类”,而后者是“构造一元函数对象”。 所以说,这两者最终都构造了一个一元函数对象,是吗?
std::logical_not
和何时使用 std::not1
!根据文档,前者是“一元函数对象类”,而后者是“构造一元函数对象”。 所以说,这两者最终都构造了一个一元函数对象,是吗?
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::not1
。在en.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";
}
unary_function
已被弃用(lambda表达式更好)。 - edmzargument_type
成员,而std::not1
需要它。 - YSC