Javatpoint Logo
Javatpoint Logo

C++ Algorithm max()

C++ Algorithm max() function can be used in following 3 ways:

  • It compares the two values passed in its arguments and returns the larger between them. If both are equal, then it returns the first one.
  • It also compares the two values using a binary function which is defined by the user, and then passed as an argument in std::max().
  • It is also used to find the largest element in a given list, and it returns the first one if there are more than one are largest in the list.

Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version.

Syntax

Parameter

a: First value to compare.

b: Second value to compare.

comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order otherwise it returns false. It follows the strict weak ordering to order the elements.

il: An initializer_list with the values to compare.

Return value

It returns the maximum of a and b. If the values are equivalent, it returns a.

Returns the largest value in il. If several values are equivalent to the maximum, returns the left most such value.

Complexity

Complexity is linear in one less than the number of elements compared.

Exceptions

This function throws an exception if any comparison throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of max():

Output:

larger of 1 and 9999: 9999
larger of 'a', and 'b': b
longest of "foo", "bar", and "hello": hello

Example 2

Let's see another simple example to demonstrate the use of max() using default version:

Output:

max(1,2)==2
max(2,1)==2
max('a','z')==z
max(3.14,2.73)==3.14

Example 3

Let's see another simple example to demonstrate the use of max() using comparison function:

Output:

28
7

Example 4

Let's see a simple example to find the maximum element in the list:

Output:

Maximum element is: 10

Next TopicC++ Algorithm




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA