📜  C++中的std :: unary_negate()与示例

📅  最后修改于: 2021-04-30 03:08:04             🧑  作者: Mango

std :: unary_negate()是一个包装函数对象,返回其持有的一元谓词的补码。包装函数是软件库或计算机程序中的子例程,其主要目的是在很少或不需要额外计算的情况下调用第二个子例程或系统调用。通常使用函数std :: not1()构造unary_negate类型的对象。

头文件:

#include 

句法:

std::unary_negate
    variable_name(Object of class T);

参数:函数std :: unary_negate()接受谓词函数对象作为参数,并返回通过调用谓词函数生成的结果的逻辑补码

返回值:通过调用谓词函数,返回结果的逻辑补码。

下面是说明函数std :: unary_negate()的程序

程序1:

// C++ program to illustrate
// std::unary_negate to find number
// greater than equals 4 in arr[]
  
#include 
#include 
#include 
#include 
using namespace std;
  
// Predicate function to find the
// count of number greater than or
// equals to 4 in array arr[]
struct gfg : unary_function {
  
    // Function returns true if any
    // element is less than 4
    bool operator()(int i)
        const
    {
        return i < 4;
    }
};
  
// Driver Code
int main()
{
    // Declare vector
    vector arr;
  
    // Insert value from 1-10 in arr
    for (int i = 1; i <= 10; ++i) {
        arr.push_back(i);
    }
  
    // Use unary_negate() to find the
    // count of number greater than 4
    unary_negate func((gfg()));
  
    // Print the count of number using
    // function count_if()
    cout << count_if(arr.begin(),
                     arr.end(), func);
    return 0;
}
输出:
7

说明:在上面的程序中,arrar arr []的元素从1到10 ,大于等于4的元素数为7。

程式2:

// C++ program to illustrate
// std::unary_negate to find number
// greater than equals 4 in arr[]
#include 
#include 
#include 
#include 
using namespace std;
  
// Given Structure
struct IsOdd_class {
  
    // Predicate of this structure
    bool operator()(const int& x)
        const
    {
        return x % 2 == 1;
    }
  
    typedef int argument_type;
  
} IsOdd_object;
  
// Driver Code
int main()
{
  
    // Use unary_negate function to
    // to find the compliment of
    // predicate declare in structure
    // IsOdd_class
    unary_negate
        IsEven_object(
            IsOdd_object);
  
    // Given array
    int arr[] = { 1, 1, 3, 9, 5 };
    int cx;
  
    // count with respect to predicate
    // generated by unary_negate()
    cx = count_if(arr, arr + 5, IsEven_object);
  
    // Print the count
    cout << "There are "
         << cx
         << " elements with even values!"
         << endl;
    return 0;
}
输出:
There are 0 elements with even values!

参考: http : //www.cplusplus.com/reference/functional/unary_negate/

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”