How to find the minimum/smallest element of a vector in C++ STL?

C++ STL | finding minimum/smallest element of a vector: Here, we are going to learn how to find minimum/smallest element of a vector?
Submitted by IncludeHelp, on May 18, 2019

Given a vector and we have to minimum/smallest element using C++ STL program.

Finding smallest element of a vector

To find a smallest or minimum element of a vector, we can use *min_element() function which is defined in <algorithm> header. It accepts a range of iterators from which we have to find the minimum / smallest element and returns the iterator pointing the minimum element between the given range.

Note: To use vector – include <vector> header, and to use *min_element() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.

Syntax:

    *min_element(iterator start, iterator end);

Here, iterator start, iterator end are the iterator positions in the vector between them we have to find the minimum value.

Example:

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };

    cout << *min_element(v1.begin(), v1.end()) << endl;

    Output:
    10

C++ STL program to find minimum or smallest element of a vector

//C++ STL program to find minimum or smallest 
//element of a vector 
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //vector
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "vector elements..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //finding the minimum element
    int min = *min_element(v1.begin(), v1.end());

    cout << "minimum/smallest element is: " << min << endl;

    return 0;
}

Output

vector elements...
10 20 30 40 50
minimum/smallest element is: 10

Related Tutorials




Comments and Discussions!

Load comments ↻






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