请举例说明何时使用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";
}
Run Code Online (Sandbox Code Playgroud)