max_element in C++
In this C++ tutorial, we are going to discuss the max_element in C++. To find the maximum element in a complete array or other container or to find the maximum element in a sub-part of an array, we can directly use max_element. (instead of using a loop to check for the largest element)
std::max_element is defined inside <algorithm> header file. It returns an iterator pointing to the largest element in a container.
If more than one element points to the largest element, then it returns an iterator to the first largest value in a container.
int* itr; itr = max_element( arr.begin(), arr.end() );
Here, itr will point to the largest element in array arr.
Algorithm
- Declare an array arr.
- Declare an iterator ‘itr’ of pointer type.
- Use
max_element()which returns a pointer type value pointed by iterator itr. - Print the value of max element in range by *itr.
CPP Code implementation to find the maximum element in container using max_element()
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int arr[]={ 23, 43, 56, 87 , 92};
int *itr ;
itr = max_element(arr ,arr+5);
cout<<*itr<<endl;
}OUTPUT
92
We can also use compare bool type to find the largest element based on our query.
CPP Code implementation of max_element() using third parameter compare of bool type
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
bool comp(int a, int b)
{
return a<b;
}
int main()
{
int arr[]={ 23, 43, 56, 87 , 92};
int *itr ;
itr = max_element(arr+1 ,arr+4, comp);
cout<<*itr<<endl;
}
OUTPUT
87
Here, we have used the range from arr+1 to arr+4 and the third parameter comp is bool type which returns true and false based on the given condition of a<b.
So, max_element makes code short and its an easy implementation for finding the largest element in a given range.
Leave a Reply