This post will discuss how to find the min or max value in a vector in C++.

1. Using std::max_element

The std::min_element and std::max_element return an iterator to the minimum and the maximum value in the specified range, respectively. The following code example shows invocation for both these functions:

Download  Run Code

 
Both these functions accept a binary predicate, which can be used to compare a vector of objects using a specific field, as shown below:

Download  Run Code

Output:

Minimum age object: (A, 10)
Maximum age object: (B, 15)

2. Using std::minmax_element

A better option is to use the std::minmax_element function to get the minimum and the maximum elements in a container. It returns a pair of iterators, with the first and second values pointing to the minimum and the maximum element, respectively.

Download  Run Code

 
To get the index of the elements with the maximum or the minimum value, apply pointer arithmetic, or call to std::distance function.

Download  Run Code

3. Using custom routine

Finally, we can write your custom routine to find the minimum and the maximum value in a vector. Here’s what the code would look like:

Download  Run Code

That’s all about finding the min or max value in a vector in C++.