當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::unary_negate()用法及代碼示例

std::unary_negate()是包裝函數對象,返回其持有的一元謂詞的補碼。包裝函數是軟件庫或計算機程序中的子例程,其主要目的是在很少或不需要額外計算的情況下調用第二個子例程或係統調用。通常使用函數std::not1()構造unary_negate類型的對象。

頭文件:

#include <functional>

用法:

std::unary_negate<class T>
    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 <algorithm> 
#include <functional> 
#include <iostream> 
#include <vector> 
using namespace std; 
  
// Predicate function to find the 
// count of number greater than or 
// equals to 4 in array arr[] 
struct gfg:unary_function<int, bool> { 
  
    // 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<int> 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<gfg> 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 <algorithm> 
#include <functional> 
#include <iostream> 
#include <vector> 
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<IsOdd_class> 
        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/




相關用法


注:本文由純淨天空篩選整理自_anupam_kumar_krishnan_大神的英文原創作品 std::unary_negate() in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。