Open In App

How to Find the Minimum and Maximum Element of a Vector Using STL in C++?

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to find the minimum and maximum element in vector in C++.

The simplest method to find the minimum and maximum element in vector is by using min_element() and max_element().  Let’s take a look at a simple example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 5, 3, 9};

    // Find the min element
    int min = *min_element(v.begin(), v.end());

    // Find the max element
    int max = *max_element(v.begin(), v.end());

    cout << "Min: " << min << endl;
    cout << "Max: " << max << endl;
    return 0;
}

Output
Min: 1
Max: 9

Explanation: The min_element() returns the minimum element of vector in the given range and max_element() returns the maximum element of vector in the specified range.

There is also another method in C++ to find the minimum and maximum element of vector using STL.

Using minmax_element()

C++ STL provides a minmax_element() function that is used to find both the minimum and the maximum element in the range in a single function call. This function returns a reference of pair object in which pair first is the minimum element and pair second is the maximum element.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 5, 3, 9};

    // Finding minimum and maximum element
    auto minmax = minmax_element(v.begin(), v.end());

    cout << "Min: " << *minmax.first << endl;
    cout << "Max: " << *minmax.second << endl;
    return 0;
}

Output
Min: 1
Max: 9

Next Article
Article Tags :
Practice Tags :

Similar Reads