一、基础用法:两个值取最大值

1.包含头文件
使用标准库的 std::max 需要包含 <algorithm> 头文件(C++11 及以上也可在 <utility> 等头文件中找到定义,但但建议 <algorithm> 最通用)。

2.语法

std::max(a, b);  // 返回 a 和 b 中的最大值

3.示例

#include <iostream>
#include <algorithm> // 包含std::max

using namespace std;

int main() {
int a = 10, b = 20;
cout << max(a, b) << endl; // 输出 20

double c = 3.14, d = 2.71;
cout << max(c, d) << endl; // 输出 3.14

char e = 'a', f = 'z';
cout << max(e, f) << endl; // 输出 'z'(字符按ASCII值比较)
return 0;
}

二、多个值取最大值(C++11 及以上)

可以通过初始化列表传递多个值,语法:

std::max({a, b, c, ...});  // 返回括号中所有值的最大值

示例:

#include <iostream>
#include <algorithm>

using namespace std;

int main() {
int x = 5, y = 15, z = 10;
cout << max({x, y, z}) << endl; // 输出 15

double p = 1.2, q = 3.4, r = 2.3;
cout << max({p, q, r}) << endl; // 输出 3.4
return 0;
}

三、自定义比较规则

max 可以接受第三个参数(比较函数/ lambda 表达式),自定义“最大值”的判定逻辑。

示例:比较两个字符串的长度,返回更长的字符串:

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main() {
string s1 = "apple", s2 = "banana";
// 第三个参数是lambda表达式:比较两个字符串的长度
auto longer_str = max(s1, s2, [](const string& a, const string& b) {
return a.size() < b.size(); // 长度小的被视为“小”
});
cout << longer_str << endl; // 输出 "banana"(长度6 > 5)
return 0;
}

四、注意事项

  1. 参数类型max 要求所有参数类型相同(或可隐式转换),否则会编译错误。

    max(10, 3.14);  // 错误:int 和 double 类型不匹配

    需手动转换类型:max(10.0, 3.14)max((double)10, 3.14)

  2. 与容器结合:如果需要求容器(如 vectorarray)中的最大值,需配合迭代器使用 std::max_element(同样在 <algorithm> 中):

    #include <vector>
    #include <algorithm>

    int main() {
    vector<int> v = {3, 1, 4, 1, 5};
    // max_element返回指向最大值的迭代器,*取值
    int max_val = *max_element(v.begin(), v.end());
    cout << max_val << endl; // 输出 5
    return 0;
    }