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


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

std::less_equals是用於執行比較的函數對象類。它被定義為小於相等比較的函數對象類,該比較類根據條件返回布爾值。它可以與各種標準算法(例如sort,lower_bound)和容器(例如矢量,集合等)一起使用。

頭文件:

#include <functional.h>

模板類別:

template <class T> struct less_equal {

  // Declaration of the 
  // less 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;
};

用法:

std::bind2nd(std::less_equal(), K)

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



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

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

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

程序1:

// C++ program to illustrate less_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 increasing order 
    sort(arr, arr + N, less_equal<int>()); 
  
    // Print sorted array 
    printArray(arr, N); 
    return 0; 
}
輸出:
0 1 2 3 4 5 6 7 8 9

程序2:

// C++ program to illustrate less_equal 
#include <functional> 
#include <iostream> 
#include <iterator> 
#include <set> 
using namespace std; 
  
// Driver Code 
int main() 
{ 
    // Initialise set with less_equal to 
    // store the elements in increasing 
    // order 
    set<int, less_equal<int> > S; 
  
    // Insert elements in S 
    S.insert(75); 
    S.insert(30); 
    S.insert(60); 
    S.insert(20); 
    S.insert(50); 
    S.insert(30); 
  
    // Print the elements stored in set S 
    for (auto& it:S) { 
        cout << it << ' '; 
    } 
  
    return 0; 
}
輸出:
20 30 30 50 60 75

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




相關用法


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