gpt4 book ai didi

c++ - std::logical_not 和 std::not1 之间的区别?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:15 27 4
gpt4 key购买 nike

请举例说明何时使用 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 的概括用于更复杂的用例。


Please explain with examples when to use std::logical_not and when 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";
}

关于c++ - std::logical_not 和 std::not1 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36033323/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com