Namespaces
Variants

std::unary_negate

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器和适配器
(直至 C++17*)
(直至 C++17*)
(直至 C++17*)
(直至 C++17*)  
(直至 C++17*)
(直至 C++17*)(直至 C++17*)(直至 C++17*)(直至 C++17*)
(直至 C++20*)
(直至 C++20*)
(直至 C++17*)(直至 C++17*)
(直至 C++17*)(直至 C++17*)

(直至 C++17*)
(直至 C++17*)(直至 C++17*)(直至 C++17*)(直至 C++17*)
(直至 C++20*)
(直至 C++20*)
 
定义于头文件 <functional>
template< class Predicate >
struct unary_negate : public std::unary_function<Predicate::argument_type, bool>;
(直至 C++11)
template< class Predicate >
struct unary_negate;
(自 C++11)
(C++17 中弃用)
(C++20 中移除)

std::unary_negate 是一个包装函数对象,返回其所持有的一元谓词的补集。

一元谓词类型必须定义一个成员类型 argument_type,该类型可转换为谓词的参数类型。从 std::ref、std::cref、std::negate、std::logical_not、std::mem_fn、std::function、std::hash 或从另一个对 std::not1 的调用所获得的一元函数对象定义了此类型,派生自弃用的 std::unary_function 的函数对象也是如此。

std::unary_negate 对象可以借助辅助函数 std::not1 轻松构造。

成员类型

类型 定义
argument_type Predicate::argument_type
result_type bool

成员函数

(constructor)
使用提供的谓词构造新的 unary_negate 对象
(公开成员函数)
operator()
返回对存储谓词调用结果的逻辑补集
(公开成员函数)

std::unary_negate::unary_negate

explicit unary_negate( Predicate const& pred );
(C++14 起为 constexpr)

构造一个std::unary_negate函数对象,其中的谓词为pred。

参数

pred - 谓词函数对象

std::unary_negate::operator()

bool operator()( argument_type const& x ) const;
(constexpr 自 C++14 起)

返回对调用 pred(x) 所得结果的逻辑补。

参数

x - 传递给谓词的参数

返回值

调用 pred ( x ) 结果的逻辑补。

示例

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
struct less_than_7 : std::unary_function<int, bool>
{
    bool operator()(int i) const { return i < 7; }
};
int main()
{
    std::vector<int> v(7, 7);
    v[0] = v[1] = v[2] = 6;
    std::unary_negate<less_than_7> not_less_than_7((less_than_7()));
    // C++11 解决方案:
    // 使用 std::function<bool (int)>
    // std::function<bool (int)> not_less_than_7 =
    //     [](int x)->bool { return !less_than_7()(x); };
    std::cout << std::count_if(v.begin(), v.end(), not_less_than_7);
}

输出:

4

参见

(C++17 中弃用) (C++20 中移除)
包装器函数对象,返回其持有的二元谓词的补集
(类模板)
(C++11)
任意可复制构造的可调用对象的可复制包装器
(类模板)
仅移动包装器,适用于支持给定调用签名中限定符的任何可调用对象
(类模板)
(C++17 中弃用) (C++20 中移除)
构造自定义的 std::unary_negate 对象
(函数模板)
(C++11 中弃用) (C++17 中移除)
从函数指针创建适配器兼容的函数对象包装器
(函数模板)
(C++11 中弃用) (C++17 中移除)
适配器兼容的一元函数基类
(类模板)