Javatpoint Logo
Javatpoint Logo

C++ Algorithm minmax()

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

  1. It compares the two values passed in its arguments and returns the smaller and larger between them, and if both are equal, then it returns make_pair (a,b).
  2. It also compares the two values using a binary function, which is defined by the user, and then passed as argument in std::minmax().
  3. It is also used to find the smallest element and largest element in a given list, and it returns the first one if there are more than one are smallest and last of them 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 and false otherwise. It follows the strict weak ordering to order the elements.

il: An initializer_list with the values to compare.

Return value

It returns the smaller as first element and larger as second element between a and b. If the values are equivalent, returns make_pair (a,b).

Returns the smallest as first and largest value as the second in il. If several values are equivalent to smaller, returns the left most such value and several values are equivalent to larger, returns the right most such value.

Complexity

Complexity is linear in one and half times the number of elements compared.

Exceptions

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

Please note that invalid parameters cause an undefined behavior.

Example 1

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

Output:

The minimum value obtained is : 23
The maximum value obtained is : 53

The minimum value obtained is : 1
The maximum value obtained is : 6

Example 2

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

Output:

minmax({1,2,3,4,5}): 1 5

Example 3

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

Output:

v[0,7]: 3 1 4 1 5 9 2

Next TopicC++ Algorithm




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA