std::max in C++

std::max in C++

Comparing values and finding the maximum is an important task in C++ programming. The std::max in C++ is a powerful standard library function that helps to find the maximum of two or more values efficiently. Whether you are comparing primitive types or custom objects, it supports various types effortlessly. In this article, we will discuss what std::max is, three versions of std::max, its syntax, parameters, return value, time complexity, working, uses, exceptions, examples, and related functions in C++.

Table of Contents:

What is std::max in C++?

What is stdmax in C++

The std::max in C++ is a standard library function that gives the larger of two values as a result. It is available in the <algorithm> header in C++, which provides a type-safe and efficient way to compare two values and get the maximum of them.

Syntax:

std::max(value1, value2);

Here, value1 and value2 are the values that are to be compared, and the larger one between them will be returned by the max() function.

Example:

Cpp

Output:

What is stdmax in C++ Example

The code shows that the two integers x=6 and y=10 are compared using the std::max, and then the larger value, 10, is printed to the console.

3 Versions of std::max Function in C++

3 Versions of stdmax Function in C++

The three main versions of the std::max() function in C++. Let’s discuss each of the versions in brief.

1. std::max(value1, value2)

This version is the basic version of the std::max() function. It takes two arguments and returns the larger value as a result of the comparison.

Syntax:

std::max(a, b);

Example:

Cpp

Output:

stdmax(value1, value2)

The code shows how the two scores, score1 and score2, are compared using the std::max returns the larger value, which is stored in the highestScore, and then the output is printed to the console.

2. std::max(std::initializer_list<T> il)

It is a version of the std::max() that helps to maximum among multiple values by using an initializer list. It has been available since C++11.

Syntax:

std::max({value1, value2, value3, ...});

Example:

Cpp

Output:

stdmax(stdinitializer)

The code shows how the std::max uses an initializer list to take the list of integers and return the largest value. Here, the top score is 93, so it is printed as a result to the console.

3. std::max(value1, value2, comp)

It is a version of the std::max() which is used to specify a custom comparison function with three arguments: value1, value2, and comp, and gives the larger value.

Syntax:

std::max(a, b, comp);

Example:

Cpp

Output:

stdmax(value1, value2, comp)

The code shows how the std::max uses a lambda comparator to compare the string length and then return the longer string, “banana”, as a result.

Parameters of std::max Function in C++

Let’s discuss the parameters of each version of the std::max() function in C++.

1. std::max(a, b)

  • a: It is the first value that is to be compared.
  • b: It is the second value that is to be compared.

In this basic version, both arguments must be of the same type and can be of any data type that is compared using the > operator.

2. std::max(std::initializer_list<T> il)

  • il: An initializer list of values.

The initializer list must contain the same type of arguments or values of type ‘T’.

3. std::max(a, b, comp)

  • a: It is the first value that is to be compared.
  • b: It is the second value that is to be compared.
  • comp: It is a comparison function used for the custom ordering.

The comp parameter only takes the values of the same data type and gives a boolean value.

Return Value of the std::max Function in C++

The std::max() function in C++ returns the larger or maximum value of two values. Let’s discuss the return value from each version of the std::max() function. 

1. std::max(a, b)

  • It returns the larger of a and b. 
  • It returns a, if a ==b.
  • The return type is the same as the argument type.

2. std::max(std::initializer_list<T> il)

  • It returns the larger value or element of the initializer list.
  • The return type is the type ‘T’, the same as the elements of the initializer list.

3. std::max(a, b, comp)

  • It returns the which is greater by using the comp function based on your custom function.
  • The return type is the same as the input values.

Time Complexity of std::max in C++

  1. The time complexity of the std::max(a, b) is O(1) because this compares only two values using the < operator.
  1. The time complexity of the std::max(a, b, comp) is also O(1) because this also only compares two values using the comp function.
  1. The time complexity of the std::max({a, b, c, …}) is O(n) because it compares multiple elements of the initializer list.
Version Description Time Complexity
std::max(a, b) Compares two values O(1)
std::max(a, b, comp) Compares two values with a comparator O(1)
std::max({a, b, c, …}) Finds the max in a list of values O(n)

Get 100% Hike!

Master Most in Demand Skills Now!

How Does the std::max Function Work in C++?

Let’s discuss the working of each version of the std::max() function in C++.

1. Basic Comparison (std::max(a, b))

This version uses the < operator internally to compare the two values, and returns b if a < b, otherwise, it returns a.

2. Custom Comparison (std::max(a, b, comp))

This version uses the custom comparator provided by the user instead of the < operator to compare the values. It returns true if a<b, otherwise, it returns a.

3. Initializer List (std::max({a, b, c, …}))

This version iterates through the elements of the initializer list and compares each element to find the maximum value, by internally calling the two-argument repeatedly.

Hence, you can say that std::max uses either the default or custom logic to compare values and return the value that is greater.

Uses of std::max Function in C++

  1. It is used to compare two numbers to find the maximum of the two values, such as scores, measurements, or timestamps.
  2. The std::max is used to find the greater of multiple values.
  3. It is used to compare the custom objects and values based on specific rules.
  4. It is also used in limiting the values within a certain range.
  5. The std::max is used in bounding box calculations, collision detection, etc.
  6. It is also used for performance optimization in C++.

Exceptions of std::max Function in C++

The std::max() function does not throw exceptions by itself. It can throw an exception depending on the type and operations.

Let’s discuss a few situations where an exception occurs using std::max().

1. When Using Custom Types

If the comparison operator (<) or the custom comparator throws an exception, the std::max will propagate that exception.

Example:

struct MyType {
bool operator<(const MyType&) const {
throw std::runtime_error("Comparison failed!");
}
};
std::max(MyType{}, MyType{}); // This will throw exception

2. When Using a Comparator

If you use a comparator function and it throws an exception, then the exception cannot be caught by the std::max.

Example:

std::max(5, 10, [](int a, int b) -> bool {
throw std::logic_error("Exception!");
return a < b;
});

3. When using an Initializer List 

If you are using an initializer list for creating or copying elements, then it can throw an exception.

Example:

std::max({MyType(), MyType()});  // If copy constructor throws, this fails

You can check this table for clear and concise information:

Situation Can Throw Exception? Description
Basic comparison (std::max(a, b)) No Unless < throws
With comparator (std::max(a, b, comp)) Yes If the comp throws
Initializer list (std::max({a, b, c})) Yes If element construction or comparison throws

Examples of std::max in C++

Below are a few examples using std::max in C++:

Example 1: Find the Maximum Value in an Array

Cpp

Output:

Find the Maximum Value in an Array

The code shows how the std::max_element is used to find the maximum value in an array, which returns an iterator *std::max_element(arr, arr+5) to the largest element.

Example 2: Clamping a Value within a Range

Cpp

Output:

Clamping a Value within a Range

The code shows how the std::max is used to clamp the value between 0 and 100. If the value is less than lowerLimit, then it becomes lowerLimit, and if the value is greater than upperLimit, then it becomes upperLimit. Then, the clamped value is printed to the console.

Example 3: Finding the Maximum Value Using a Comparison Function

Cpp

Output:

Finding the Maximum Value Using a Comparison Function

The code shows how the std::max() with a lambda comparator is used to find the top student with higher marks from three Student objects, and then the result is printed to the console.

Below are a few functions that are related to the std::max function in C++ and are used for comparisons and finding the extremes.

1. std::min() in C++

The std::min() function is used to find the smaller of two values. It also has three versions like std::max.

Syntax:

T std::min(const T& a, const T& b);

Example:

Cpp

Output:

stdmin() in C++

The code shows how the std::min() is used to find and print the smaller of two integers a and b, and then returns 5 as a result of the comparison to the console.

2. std::minmax() in C++

The std::minmax() in C++ function returns both the minimum and maximum of two values in a single call of the function.

Syntax:

std::pair<T, T> std::minmax(const T& a, const T& b);

Example:

Cpp

Output:

stdminmax() in C++

The code shows how the std::minmax() is used to find the smallest and largest of two values and returns them as a pair, and then the result.first prints the minimum and the result.second prints the maximum.

3. std::clamp() in C++17

The std::clamp() function is used to restrict a value to be in a given range, not less than the lower bound nd not more than the upper bound.

Syntax:

T std::clamp(const T& value, const T& low, const T& high);

Example:

Cpp

Output:

stdclamp() in C++17

The code shows how the std::clamp() is used to restrict the value between the given low and high values. If the value is below low, then it will return low, and if the value is above high, then it will return high.

4. std::max_element() and std::min_element() in C++

The std::max_element() and std::min_element() in C++ return iterators to the maximum and minimum element in a given range.

Syntax:

// Find max element
auto it = std::max_element(start, end);
// Find min element
auto it = std::min_element(start, end);

Example:

Cpp

Output:

stdmax_element() and stdmin_element() in C++

The code shows how the std::max_element and the std::min_element are used to scan and return iterators to the largest and smallest element, and then print to the console.

Conclusion

The std::max() function in C++ helps to find the maximum of two or more values easily. It has three main versions which you can use according to your needs. It supports every type of data type, such as integer, double, or custom data types. It is also used in many real-life applications. So, by understanding what std::max is, how it works, what it returns, its use cases, complexity, and related functions, you can easily use all three versions of std::max in C++.

FAQs on std::max in C++

Q1. What does std::max do in C++?

The std::max in C++ finds and returns the larger of two values using the < operator or a custom comparator.

Q2. Which header is required for std::max?

You need to include the header for the std::max in your code.

Q3. Can std::max compare more than two values?

Yes, the std::max can compare more than two values by using the initializer list version, std::max({a, b, c, …}).

Q4. Can I use std::max with custom types?

Yes, you can use the std::max wth custom types if you overload < or provide a custom comparator.

Q5. Is std::max exception-safe?

Yes, it is safe unless your comparison logic and type constructors throw exceptions.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner