std::max_element() function with example in C++ STL

C++ STL | std::max_element() function: Here, we are going to learn about the max_element() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 20, 2019

C++ STL std::max_element() function

max_element() function is a library function of algorithm header, it is used to find the largest element from the range, it accepts a container range [start, end] and returns an iterator pointing to the element with the largest value in the given range.

Additionally, it can accept a function as the third argument that will perform a conditional check on all elements.

Note: To use max_element() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

Syntax of std::max_element() function

    std::max_element(iterator start, iterator end, [compare comp]);

Parameter(s):

  • iterator start, iterator end – these are the iterator positions pointing to the ranges in the container.
  • [compare comp] – it's an optional parameter (a function) to be compared with elements in the given range.

Return value: iterator – it returns an iterator pointing to the element with the largest value in the given range.

Example:

    Input:
    int arr[] = { 100, 200, -100, 300, 400 };
    
    //finding largest element
    int result = *max_element(arr + 0, arr + 5);
    cout << result << endl;
    
    Output:
    400

C++ STL program to demonstrate use of std::max_element() function

In this program, we have an array and a vector and finding their largest elements.

//C++ STL program to demonstrate use of
//std::max_element() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //an array
    int arr[] = { 100, 200, -100, 300, 400 };

    //a vector
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //finding largest element from the array
    int result = *max_element(arr + 0, arr + 5);
    cout << "largest element of the array: " << result << endl;

    //finding largest element from the vector
    result = *max_element(v1.begin(), v1.end());
    cout << "largest element of the vector: " << result << endl;

    return 0;
}

Output

largest element of the array: 400
largest element of the vector: 50

Reference: C++ std::max_element()




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.