min_element() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). min_element() is a method in the STL that returns an iterator pointing to the smallest value in a given container (arrays, vectors, lists) in the specified range.

Syntax

min_element(iterator_begin, iterator_end); //find smallest element from [begin,end)
min_element(iterator_begin, iterator_end, comparator); //for comparison based on a defined function

Parameters: The min_element() method accepts 3 parameters

  • iterator_begin: Random access iterator to the initial position
  • iterator_end: Random access iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: An iterator to the smallest value in the range, or iterator_end if the range is empty.

Example of min_element() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

bool absolute(int a, int b)
{
    return (abs(a) < abs(b));
}


int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(6);
    v.push_back(8);
    v.push_back(-3);
    v.push_back(-10);

    vector<int>::iterator it = min_element(v.begin(),v.end());
    cout<<"Min element: "<< *it << endl;

    vector<int>::iterator it2 = min_element(v.begin(), v.end(), absolute);
    cout<<"Min element (absolute): "<< *it2 << endl;
}

Output:

Min element: -10
Min element (absolute): 1

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top