Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ algorithm::minmax_element function is used to return a pair with an iterator pointing to the smallest element in the range [first,last) as pair::first, and largest as pair::second. The elements are compared using operator< (in first version) or comp (in second version).

Syntax

//default version
template <class ForwardIterator>
  pair<ForwardIterator,ForwardIterator> 
    ForwardIterator minmax_element (ForwardIterator first, 
                                    ForwardIterator last);

//custom version
template <class ForwardIterator, class Compare>
  pair<ForwardIterator,ForwardIterator>
    ForwardIterator minmax_element (ForwardIterator first, 
                                    ForwardIterator last,
                                    Compare comp);

Parameters

first Specify initial position of the forward iterator of the sequence to compare. The range used is [first,last).
last Specify final position of the forward iterator of the sequence to compare. The range used is [first,last).
comp A binary predicate that takes two elements in the range as arguments and returns a value convertible to bool. The returned value indicates whether the first argument is considered less than the second.

Return Value

Returns a pair with an iterator pointing to the smallest element in the range [first,last) as pair::first, and largest as pair::second.

Time Complexity

Up to 1.5 times of Linear i.e, Θ(1.5*n).

Example:

In the below example, the algorithm::minmax_element function is used to find out the smallest and largest elements in the given range.

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

int main (){
  int Arr[] = {10, 5, 15, 45, 20, 55};
  pair<int*, int*> MinMax;

  //finding minimum and maximum elements in the array
  MinMax = minmax_element(Arr, Arr+6);
  cout<<"The minimum element in Arr: "<<*MinMax.first;
  cout<<"\nThe maximum element in Arr: "<<*MinMax.second;

  return 0;
}

The output of the above code will be:

The minimum element in Arr: 5
The maximum element in Arr: 55

Example:

The below example shows how to use comp with algorithm::minmax_element function.

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

bool less_than (int i, int j) {
  return (i<j);
}

int main (){
  vector<int> vec= {10, 5, 15, 45, 20, 55};
  pair<vector<int>::iterator, vector<int>::iterator> MinMax;

  //finding minimum and maximum elements in the vector
  MinMax = minmax_element(vec.begin(), vec.end(), less_than);
  cout<<"The minimum element in vec: "<<*MinMax.first;
  cout<<"\nThe maximum element in vec: "<<*MinMax.second;

  return 0;
}

The output of the above code will be:

The minimum element in vec: 5
The maximum element in vec: 55

❮ C++ <algorithm> Library