Home »
C++ STL
Minimum and maximum elements of a vector in C++ STL
C++ STL | finding minimum and maximum elements of a vector: Here, we are going to learn how we can find the minimum and maximum elements of a given vector?
Submitted by IncludeHelp, on May 17, 2019
Given a vector and we have to find the smallest (minimum) and largest (maximum) elements.
Finding vector's minimum & maximum elements
To find minimum element of a vector, we use *min_element() function and to find the maximum element, we use *max_element() function.
Syntax:
*max_element(iterator start, iterator end);
*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 and maximum value.
These functions are defined in <algorithm> header or we can use <bits/stdc++.h> header file.
Example:
Input:
vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };
cout << *min_element(v1.begin(), v1.end()) << endl;
cout << *max_element(v1.begin(), v1.end()) << endl;
Output:
10
50
C++ STL program to find minimum and maximum elements of a vector
//C++ STL program to append a vector to a vector
#include <bits/stdc++.h>
using namespace std;
int main()
{
//vector declaration
vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };
int min = 0;
int max = 0;
//finding minimum & maximum element
min = *min_element(v1.begin(), v1.end());
max = *max_element(v1.begin(), v1.end());
cout << "minimum element of the vector: " << min << endl;
cout << "maximum element of the vector: " << max << endl;
return 0;
}
Output
minimum element of the vector: 10
maximum element of the vector: 50