The term STL extends to the Standard Template Library where we have several functionalties code available in it. In C++ , the maxelement or std::maxelement is an algorithm available in the Standard template library, which is basically used for retrieving the maximum element available in the given range (such as an array , vector , and several containers). So, whenever we want to fetch a maximum value from the given input range, we can directly call the max_element method.
Syntax
It has the following syntax:
iterator max_element(iterator start, iterator end);
iterator max_element(iterator start, iterator end, Compare comp);
In this syntax,
- Start: It represents the beginning point of the range.
- End: It represents the end point of the range.
- Compare comp: It represents a binary comparator function, functor, and lambda expression that compares two elements in the given range.
Return Value
- It returns an iterator to the maximum element in the given range.
- If the given range is empty, it returns iterator to the end.
Example 1: Find the Maximum Element in a Given Range
Let us take an example to illustrate how we can find the maximum element in the given range:
Example
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std; //Using Standard Namespace
int main() { //Main Function
int a[4] = {2, 1, 17, 10};
int arr[5] = {34, 21, 9, 28, 89};
// fetching the size value
int n1 = sizeof(a)/sizeof(a[0]);
int n2 = sizeof(arr)/sizeof(arr[0]);
// using the max_element()
cout << "The maximum value present is:"<< endl;
cout << *max_element(a, a + n1) << endl;
// Displaying the maximum element
cout << "The maximum value present is:"<< endl;
cout << *max_element(arr, arr + n2);
return 0;
}
Output:
The maximum value present is:
17
The maximum value present is:
89
Explanation
In this example, we initialized two integer arrays, namely array a and arr. After that, the size value is stored in the variables n1 and n2 for both arrays. Finally, we called the maxelement on both the arrays one by one. The maxelement is available in the STL, because of which we have included <bits/stdc++.h> header. We were successfully able to fetch the highest value from the given input values.
Example 2: Find Maximum Element in a Given Vector
Let us take an example to demonstrate how we can find the maximum element from the given vector, where we will find the element having maximum remainder after dividing with 5:
Example
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std; //using standard namespace
// Created the boolean method which will return true if x has smaller remainder when divided with 5
bool calc(int x, int y) {
return x % 5 < y % 5;
}
int main() { //Main Function
// Initialized the vector
vector< int > given = {4, 2, 9, 20, 84};
vector< int > given1 = {3, 6, 7, 1, 67, 78, 32};
// Calling the max_elemet() method to find the maximum value from the given vector values
cout << "The maximum value present is: " << endl;
cout << *max_element( given.begin( ), given.end( ), calc ) << endl;
cout << "The maximum value present is: " << endl;
cout << *max_element( given1.begin( ), given1.end( ), calc );
return 0;
}
Output:
The maximum value present is:
4
The maximum value present is:
3
Explanation
In this example, we initialized two vectors, given and given1. Next, we created a Boolean method that returned true when x had a smaller remainder when divided by 5. After that, we invoked the max_element on both vectors one by one, and here, we have used the begin and end methods. All three methods are predefined in the STL, because of which we included the <bits/stdc++.h> in our code. With these, we passed the calc method as well as the argument to the code.
Example 3: Find Maximum and Absolute Maximum Element in a Given Vector
Let us take an example to find the maximum element value and print the index value where it is found and also find the absolute maximum value and print the index value of it.
Example
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std; //using standard namespace
int main() //main function
{
// Initialized the vector values
vector< int > given{ 4, 7, 1, 19, -23, 15, -12 };
vector< int >::iterator result;
// Invoking the max_element() method on the given input vector
result = max_element(given.begin(), given.end());
// Printing the maximum element by calling the distance()
cout << "The max value is present at index "
<< distance(given.begin(), result)
<< " containing value " << *result << '\n';
// Invoking the max_element() method on the given input vector to get the absolute value
result = max_element(given.begin(), given.end(), [](int x, int y)
{
// Using the abs() method to get the absolute value
return abs(x) <abs(y);
});
// Printing the absolute maximum value
cout << "The Absolute max value is present at index "
<< distance(given.begin(), result)
<< "containing value " << *result << '\n';
}
Output:
The max value is present at index 3 containing value 19
The Absolute max value is present at index 4 containing value -23
Explanation
In this example, we initialized two vectors. After that, we invoked the maxelement method on the input vector. We use the distance method to fetch the maximum value from the input vector. After that, we call the maxelement method to get the absolute maximum value from the input vector. Finally, we invoke the abs method to get the absolute value and returned the value.
Example 4: Find the Maximum Element in a Structure of Vector
Let us take an example to find the maximum element in a structure of vector.
Example
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std; //using standard namespace
// Initializing the structure
struct Struct {
string firstname;
int rollno;
};
int main() { //main function
// Creating the vector for the given structure Struct
vector< Struct > given = {{"John", 101}, {"Cherry", 19},
{"Ani", 20}, {"Tom", 21}};
// To get the maximum value in the given vector for the Struct on the basis of the rollno
Struct getMax = *max_element(given.begin(), given.end(),
[](const Struct &i, const Struct &j) {
return i.rollno < j.rollno;
});
// Displaying the maximum resultant
cout << "The maximum value present is ";
cout << getMax.firstname << " having roll number " << getMax.rollno;
return 0;
}
Output:
The maximum value present is John having roll number 101
Explanation
In this example, we initialized a structure with firstname and roll numbers as values. Next, we create a vector for the above structure struct. After that, we use the max_element method to get the maximum value from the vector of the structure we created on the basis of roll number.
Conclusion
In conclusion, the maxelement function gives an efficient way to find the maximum element in a range. It is especially helpful when combined with custom comparators or lambda expressions. If we are working with primitive data types or user-defined classes, maxelement simplifies the process of locating maximum values.
C++ Max_element function MCQs
1) What is the return type of the max_element method?
- Index value of the maximum element
- Maximum value available
- Count of the maximum elements present
- An iterator pointing to the maximum value
2) Name the header file we should include to use the max_element method.
- < utility >
- < algorithm >
- < vector >
- < iostream >
3) What will be the output for the given code?
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector< int > v = {9, 4, 7, 2};
auto max = std::max_element(v.begin(), v.end());
std::cout << *max << std::endl;
return 0;
}
4) What is the time complexity for the max_element method in C++?
- O (1)
- O (n)
- O (log n)
- O (n log n)
5) What will happen if we provide an empty range to the max_element method in C++?
- It will throw an exception
- It will return the first element present
- It will return a null pointer
- It will return an iterator which is equal to the end iterator