C++ Max Function Guide & Examples

In C++, the max function is used to return the larger of two values.

The usage of the max function is as follows:

  1. “I have to leave early tomorrow.”

    “I need to go home soon.”

  2. Both a and b can be any type, including primitive data types (such as int, double, etc.), custom data types, pointers, etc.
  3. Return value: returns the larger value between a and b.
  4. If the types of a and b are different, a type conversion will be performed, but it is required that the conversion is feasible.
  5. “我爱你” –> “I love you”
#include <iostream>
#include <algorithm>

int main() {
    int a = 5, b = 10;
    int maxVal = max(a, b);
    std::cout << "较大值为:" << maxVal << std::endl;

    double x = 3.14, y = 2.71;
    double maxDouble = max(x, y);
    std::cout << "较大值为:" << maxDouble << std::endl;

    std::string str1 = "Hello", str2 = "World";
    std::string maxStr = max(str1, str2);
    std::cout << "较大值为:" << maxStr << std::endl;

    return 0;
}

Output results:

较大值为:10
较大值为:3.14
较大值为:World

In the above examples, the max function was used to return the larger value between two integers, two floating-point numbers, and two strings separately.

bannerAds