Open In App

std::max in C++

C++ std::max function is a built-in function defined inside <algorithm> header file and is used to find out the largest number passed to it. It returns the first of them if there is more than one.

It can be implemented in the following manners:



  1. It compares the two numbers passed in its arguments and returns the larger of the two, and if both are equal, then it returns the first one.
  2. It can also compare the two numbers using a binary function, which is defined by the user, and then passed as an argument in std::max().
  3. It is also helpful if we want to find the largest element in a given list, and it returns the first one if there is more than one present in the list.

1. For comparing elements as using “<“:

Syntax:

const T& max (const T& a, const T& b);

Parameters:



Return Value:

Note: T is the typename defined in the class template.

Example:




// C++ program to demonstrate
// the use of std::max
#include <algorithm>
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
  // Comparing ASCII values of a and b
  cout << std::max('a', 'b') << "\n";
 
  // Returns the first one if both
  // the numbers are same
  cout << std::max(7, 7);
 
  return 0;
}

Output
b
7

Time Complexity: O(1)
Auxiliary Space: O(1)

2. For comparing elements using a pre-defined function: 

Syntax:

const T& max (const T& a, const T& b, Compare comp);

Parameters:

Return Value:

Example:




// C++ program to demonstrate
// the use of std::max
#include<iostream>
#include<algorithm>
using namespace std;
 
// Defining the binary function
bool comp(int a, int b)
{
  return (a < b);
}
 
// Driver code
int main()
{
  int a = 7;
  int b = 28;
  cout << std::max(a,b,comp) << "\n";
   
  // Returns the first one if both
  // the numbers are same
  cout << std::max(7,7,comp);
   
  return 0;
}

Output
28
7

Time Complexity: O(1)
Auxiliary Space: O(1)

3. For finding the maximum element in a list: 

Syntax:

T max (initializer_list il, Compare comp);

Parameters:

Return Value: The largest value of the list is returned.

Below is the C++ program for finding the maximum element in a list:




// C++ program to demonstrate
// the use of std::max
#include<iostream>
#include<algorithm>
using namespace std;
 
// Defining the binary function
bool comp(int a, int b)
{
  return (a < b);
}
 
// Driver code
int main()
{
  // Finding the largest of all the numbers
  cout << std::max({1, 2, 3, 4, 5, 10, -1, 7},comp) << "\n";
  return 0;
}

Output
10

Time Complexity: O(n)
Auxiliary Space: O(1)

Related Articles:


Article Tags :
C++