📜  在C++中带有示例的std :: less

📅  最后修改于: 2021-05-30 04:05:10             🧑  作者: Mango

std :: less是a是用于执行比较的功能类()的成员。它被定义为小于不等式比较的函数对象类,不等式比较根据条件返回布尔值。这可用于更改给定函数。它可以与各种标准算法一起使用,例如sort,lower_bound等。

头文件:

#include 

模板类别:

template  struct less {

  // Declaration of the less 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::less()

参数:此函数接受参数T的类型作为参数,以供功能调用进行比较。

返回类型:根据条件返回布尔值(让a和b为2个元素):

  • 正确:如果a小于b。
  • False:如果a大于b。

下面是C++中std :: less的图示:

程序1:

// C++ program to illustrate
// std::less function
#include 
#include 
#include 
using namespace std;
  
// Function to print array arr[]
void printArray(int arr[], int N)
{
  
    for (int i = 0; i < N; i++) {
        cout << arr[i] << ' ';
    }
}
  
// Driver Code
int main()
{
    int arr[] = { 26, 23, 21, 22,
                  28, 27, 25, 24 };
  
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Sort the array in increasing order
    sort(arr, arr + N, less());
  
    // Print sorted array
    printArray(arr, N);
    return 0;
}
输出:
21 22 23 24 25 26 27 28

程式2:

// C++ program to illustrate less
#include 
#include 
#include 
using namespace std;
  
// Template
template  >
  
// Function to check if a < b or not
bool f(A a, B b, U u = U())
{
    return u(a, b);
}
  
// Driver Code
int main()
{
    int X = 1, Y = 2;
  
    // If X is less than Y or not
    cout << std::boolalpha;
    cout << f(X, Y) << '\n';
  
    X = 2, Y = -1;
  
    // If X is less than Y or not
    cout << f(X, Y) << '\n';
  
    return 0;
}
输出:
true
false

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

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