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

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

C++ STL std::min_element() function

min_element() function is a library function of algorithm header, it is used to find the smallest element from the range, it accepts a container range [start, end] and returns an iterator pointing to the element with the smallest 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 min_element() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

Syntax of std::min_element() function

    std::min_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 smallest value in the given range.

Example:

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

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

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

//C++ STL program to demonstrate use of 
//std::min_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 smallest element from the array
    int result = *min_element(arr + 0, arr + 5);
    cout << "smallest element of the array: " << result << endl;

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

    return 0;
}

Output

smallest element of the array: -100
smallest element of the vector: 10

Reference: C++ std::min_element()





Comments and Discussions!

Load comments ↻






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