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


C++ std::greater_equal用法及代碼示例

std::greater_equal是函數類(<functional.h>)的成員。它用於生成類似於運算符(≥)的比較結果。該函數相對於運算符(≥)的優勢在於,它使用嚴格的總階來生成結果,而不是使用偏序的運算符(≥)。它根據條件返回布爾值。它可用於比較整數,字符或字符串等。

頭文件:

#include <functional.h>

模板類別:

template <class T> struct greater_equal {

  // Declaration of the
  // greater equal operation 
  bool operator() (const T& x, const T& y) 
       const 
  {
      return x>=y;
  }

  // Type of first parameter
  typedef T first_argument_type;

  // Type of second parameter
  typedef T second_argument_type;

  // The result is returned
  // as bool type
  typedef bool result_type;
};

參數:該函數接受參數T的類型作為參數,以供函數調用進行比較。

返回類型:它根據條件返回布爾值(讓a和b為2個元素):



  • 真正:如果a大於等於b。
  • 假:如果a小於b。

下麵是C++中std::greater_equal的圖示:

程序1:

// C++ program to illustrate greater_equal 
  
#include <algorithm> 
#include <functional> 
#include <iostream> 
using namespace std; 
  
// Function to print the array arr[] 
void printArray(int arr[], int N) 
{ 
  
    for (int i = 0; i < N; i++) { 
        cout << arr[i] << ' '; 
    } 
} 
  
// Driver Code 
int main() 
{ 
    int arr[] = { 1, 5, 8, 9, 6, 
                  7, 3, 4, 2, 0 }; 
  
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    // Sort the array in decreasing order 
    sort(arr, arr + N, greater_equal<int>()); 
  
    // Print sorted array 
    printArray(arr, N); 
    return 0; 
}
輸出:
9 8 7 6 5 4 3 2 1 0

程序2:

// C++ program to illustrate greater_equal 
  
#include <algorithm> 
#include <functional> 
#include <iostream> 
using namespace std; 
  
// Driver Code 
int main() 
{ 
  
    int arr[] = { 30, 40, -50, 60, -70, 
                  10, 20, -80, 90, 100 }; 
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    // Print the number of elements less 
    // than 0 
    cout << count_if( 
        arr, arr + N, 
        bind2nd(greater_equal<int>(), 
                0)); 
    return 0; 
}
輸出:
7

參考: http://www.cplusplus.com/reference/functional/greater_equal/




相關用法


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