# Max Operator function in C++

Hello folks! In this tutorial, we are going to learn and implement the max operator function in C++.  So let’s know a bit about what is max operator function (std::max) in C++.

Max Operator function  (std::max) is defined as the function which is used to find the largest number among the given numbers passed to it.

std::max comes under the #include<algorithm> header file.

It can be used in 3 ways listed below:

## Compare two numbers only using std::max

1. In this way, two numbers are given in the arguments we will get the largest number out of them by using std::max. Just in case both the numbers have the same value it will always return the first value. This is a simple method to use max operator function.

C++ Code

```#include<iostream>
#include<algorithm>
using namespace std;
int main()
{

cout << std::max('x','y') << "\n"; // two variables used

cout << std::max(17,34);  // values of two variables , will return largest value.

return 0;
}
```

Output:

```y
34```

Explanation to the code

First we will use #include<algorithm> header file. After that, we will use std::max function which will compare the values of variables x and y. Then we will put the values of x and y in std:: max operator. std::max operator will return the value of the largest number ie. in this case y=34.

## To find the largest number using binary function and std::max

2. In this way we will be using a binary function already defined by the user and after that, we will pass the arguments.

C++Code

```#include<iostream>
#include<algorithm>
using namespace std;

bool comp(int x, int y) // binary function defining variables x and y
{
return (x < y);
}
int main()
{
int x = 189;
int y = 278;

cout << std::max(x,y,comp) <<"\n" ; //using std::max

return 0;
}```

Output:

`278`

Explanation to the code:

First, we will be using #include<algorithm> header file. Then we will be defining a binary function, we will take two variables x and y. Then we will take values of two variables x and y and then we will be using std:: max operator function which will return largest among both values x and y.

## To find the maximum element in a list using std::max

C++ Code

```#include<iostream>
#include<algorithm>
using namespace std;

int main()
{

cout << std::max({101, 245, 378, 480, 543, 1033, -166, 7111}) << "\n"; //return the largest number in list

return 0;
}```

Output:

`7111`

Explanation of the code:

We will put header file #include<algorithm> then we will put 10 elements in the std::max it will return the largest number in the given list.

Like in this case, 7111 is the largest number on the list.