How to Find Minimum Element in a Vector in C++?
Last Updated :
19 Feb, 2024
In C++, a vector container is a dynamic array that stores its element in a contiguous memory location. In this article, we will learn how to find the minimum element in a vector in C++.
For example,
Input:
myVector={ 1, 50, 54, 72, 86, 12 }
Output:
Minimum Element is: 1
Find Minimum Value in a Vector in C++
To find the minimum element in a std::vector container, we can use the std::min_element() function provided in STL. This function takes the iterator to the first and last of the range and returns the iterator to the minimum element in the range.
Syntax to Use min_element()
min_element (first_index, last_index);
C++ Program to Find the Minimum Element in a Vector
The below example demonstrates the use of min_element() to find a minimum element in a vector in C++.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 50, 54, 72, 86, 12 };
auto min
= min_element(myVector.begin(), myVector.end());
cout << "Minimum Element is:" << *min;
return 0;
}
|
Output
Minimum Element is:1
Time Complexity: O(n) , for using the min_element() function.
Auxiliary Space: O(1)
Note: We can also use std::min
with std::accumulate
to find the minimum element in a vector in STL.
Share your thoughts in the comments
Please Login to comment...