What is the usage of std::max in C++?
std::max is a function template in the C++ standard library that is used to compare two values and return the greater value.
The std::max function template has multiple overloaded versions that can be used to compare values of different types. Some commonly used versions include:
- std::max(a, b) function compares the values of a and b, and returns the greater value. Both a and b can be of the same type or types that can be implicitly converted to the same type.
- std::max(a, b, comp): Compares the sizes of a and b using a custom comparison function comp. Comp is a callable object (such as a function pointer, function object, or lambda expression) that takes two parameters and returns a value that can be converted to a bool type, indicating the relationship between a and b. If comp(a, b) returns true, then a is considered greater than b; otherwise, b is considered greater than or equal to a.
- Find and return the largest value in the initialization list “ilist”. This version can be used to compare multiple values.
Example of using std::max:
#include <iostream>
#include <algorithm>
int main() {
int a = 5;
int b = 10;
int max_value = std::max(a, b);
std::cout << "Max value: " << max_value << std::endl;
double x = 3.14;
double y = 2.718;
double max_value2 = std::max(x, y);
std::cout << "Max value: " << max_value2 << std::endl;
auto comp = [](int a, int b) { return a % 10 < b % 10; };
int max_value3 = std::max(a, b, comp);
std::cout << "Max value: " << max_value3 << std::endl;
int max_value4 = std::max({1, 2, 3, 4, 5});
std::cout << "Max value: " << max_value4 << std::endl;
return 0;
}
Output result:
Max value: 10
Max value: 3.14
Max value: 5
Max value: 5