STL algorithms

10.4 - Min element and max element


The problem with std::max and std::min is if we want to get the max/min value of more than two numbers, we need to use the initializer list version that doesn't work with containers like std::vector.

Thankfully, there are std::max_element and std::min_element for this purpose. Unlike std::max and std::min, they return an iterator to the value, not the value itself. To get the value pointed by the iterator, we can the de-reference * operator:

auto it = std::max_element(v.begin(), v.end());
std::cout << *it << std::endl;

Use std::max_element and std::min_element if the size of the container is unknown.

Task

Write a program which takes multiple integers and prints out the value of the maximum and minimum elements in a line each.

  • Get the integers using std::cin inside a while loop.
  • Get the iterators to the max value and the min value using std::max_element and std::min_element.
  • Print out the values pointed by the iterators using the de-reference operator *.
#include <iostream> #include <vector> #include <algorithm> int main() { }