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>
.
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.
The min_element()
returns an iterator that points to the smallest element in the array.
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;}
min_element()
function and pass the required parameters.We used
*it
to print the element as the function returns a pointer to the smallest element.