How to use the min_element() function in C++
The min_element() function in C++ accepts a list of values and returns the iterator that points to the smallest value among all the elements in the list. This function is available in <algorithm.h>.
Parameters
The min_element() function accepts the following parameters.
-
first: This is the iterator that points to the start of the array or vector where we want to find the minimum. -
second_value: This is the iterator that points to the last position of the array or vector where we want to find the minimum. -
comparator: This is an optional parameter that specifies the condition to pick the element from the array. In other words, you can pass a function that accepts two values and returns a Boolean value that denotes which value to pick out of the two given values.
Return
The min_element() returns an iterator that points to the smallest element in the array.
Code
Let’s look at the code now.
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main() {vector<int> vec = {3,7,2,5,6,4,9};auto it = min_element(vec.begin(), vec.end());cout << "The smallest element is " << *it;return 0;}
Explanation
- From lines 1 to 3, we import the required header files.
- In line 7, we create a vector of integers.
- In line 9, we call the
min_element()function and pass the required parameters. - Finally, in line 10, we print the smallest element in the vector.
We used
*itto print the element as the function returns a pointer to the smallest element.