前言
在 C++ 中,std::max 是一个用于比较两个值并返回较大者的函数模板。它是 C++ 标准库中 头文件的一部分。std::max 有几个重载,可以不同以不同的方式使用std::max,可以根据需求来适应不同的情况。
一、基本使用比较
最基本的 std::max 使用: std::max 输入两个参数,并返回这两个参数(a,b)中的较大值。
#include <algorithm>
#include <iostream>
int main() {
int a = 10;
int b = 20;
int maximum = std::max(a, b);
std::cout << "The maximum value is: " << maximum << std::endl;
}
输出结果:
二、自定义函数比较
使用std::max 函数的一个重载方式,允许你提供一个自定义的比较函数。这使得std::max 不仅能够比较基本数据类型,还能根据特定的规则比较比较复杂的数据类型或对象。
例子中,在customCompare 函数中定义std::max 如何比较两个整数。
#include <algorithm>
#include <iostream>
bool customCompare(int a, int b) {
return a > b;
}
int main() {
int a = 10;
int b = 20;
int maximum = std::max(a, b, customCompare);
std::cout << "The maximum value is: " << maximum << std::endl;
}
输出结果:
二、使用 Lambda 表达式比较
从 C++11 开始,可以使用 lambda 表达式作为比较函数:
#include <algorithm>
#include <iostream>
int main() {
int a = 10;
int b = 20;
int maximum = std::max(a, b, [](int a, int b) { return a < b; });
std::cout << "The maximum value is: " << maximum << std::endl;
}