std::logical_not和std::not1有什么区别?

5
请用例子说明何时使用 std::logical_not 和何时使用 std::not1
根据文档,前者是“一元函数对象类”,而后者是“构造一元函数对象”。 所以说,这两者最终都构造了一个一元函数对象,是吗?
1个回答

7
两者都是函数对象(一个具有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_notstd::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表达式更好)。 - edmz
问题是,lambda没有argument_type成员,而std::not1需要它。 - YSC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接