Max Element In C++ STL - C++ Programming Tutorial
C++ Course / STL Basics / Max Element In C++ STL

Max Element In C++ STL

BLUF: Mastering Max Element In C++ STL is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Max Element In C++ STL

C++ is renowned for its efficiency. Learn how Max Element In C++ STL enables low-level control and high-performance computing in the tutorial below.

The acronym STL stands for the Standard Template Library, which contains a variety of useful functions. Within C++, there exists an algorithm known as maxelement or std::maxelement within the Standard Template Library. This algorithm is designed to identify and retrieve the highest element within a specified range, which could be an array, a vector, or other types of containers. Therefore, when the need arises to obtain the maximum value from a particular set of inputs, one can simply invoke the max_element function.

Syntax

It has the following syntax:

Example

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.

It provides an iterator pointing to the highest element within the specified range. In case the range is devoid of elements, it will return an iterator pointing to the end.

Example 1: Find the Maximum Element in a Given Range

Let's consider a scenario to demonstrate how we can identify the highest element within a specified range:

Example

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:

Output

The maximum value present is:
17
The maximum value present is:
89

Explanation

In this instance, we declared two integer arrays, specifically named array a and arr. Subsequently, the size parameter is assigned to the variables n1 and n2 for each array correspondingly. Ultimately, we invoked the maxelement function on each array sequentially. The maxelement function is part of the Standard Template Library (STL), which necessitated the inclusion of the <algorithm> header. We effectively retrieved the maximum value from the provided input values.

Example 2: Find Maximum Element in a Given Vector

Let's consider an example to illustrate how we can determine the largest element in a vector by finding the element with the highest remainder when divided by 5:

Example

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:

Output

The maximum value present is:
4 
The maximum value present is:
3

Explanation

In this instance, we declared two vectors, named given and given1. Following that, we established a Boolean function that evaluates to true if the remainder of x divided by 5 is lesser. Subsequently, we called the max_element function on each vector sequentially, utilizing the begin and end functions. These three functions are part of the standard template library (STL), which is why we imported the <bits/stdc++.h> in our code. Alongside these actions, we also provided the calc function and its corresponding argument within the code.

Example 3: Find Maximum and Absolute Maximum Element in a Given Vector

Let's consider a scenario where we aim to identify the highest element value in a list, display the index where it is located, and determine the absolute maximum value along with its corresponding index position.

Example

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:

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 instance, two vectors were initialized. Subsequently, the maxelement function was called on the initial vector. The distance function was utilized to retrieve the maximum value from the initial vector. Following this, the maxelement function was invoked to obtain the absolute maximum value from the initial vector. Lastly, the abs function was called to acquire the absolute value, which was then returned.

Example 4: Find the Maximum Element in a Structure of Vector

Let's consider an example to determine the highest value in a vector data structure.

Example

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:

Output

The maximum value present is John having roll number 101

Explanation

In this instance, we instantiated a data structure with first names and student ID numbers as data points. Subsequently, we instantiated a vector for the aforementioned data structure. Following this, we employed the max_element function to retrieve the highest value from the vector containing the data structure based on the student ID numbers.

Conclusion

In summary, the maxelement function offers a convenient method for identifying the highest element within a specified range. This functionality becomes particularly valuable when utilized in conjunction with bespoke comparators or lambda functions. Whether handling primitive data types or custom classes, maxelement streamlines the task of pinpointing 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?

Example

#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

Selecting option d) will result in the return of an iterator that is equivalent to the end iterator.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience