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++
// C++ program to find the minimum element in a vector #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { // Initializing the vector vector< int > myVector = { 1, 50, 54, 72, 86, 12 }; auto min = min_element(myVector.begin(), myVector.end()); // Finding the minimum element and printing it 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
withstd::accumulate
to find the minimum element in a vector in STL.
How to Find Minimum Element in a Vector in C++?
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
Contact Us