Cover Image for std::minmax() and std::minmax_element() in C++ STL
182 views

std::minmax() and std::minmax_element() in C++ STL

The C++ STL (Standard Template Library), you can use std::minmax() and std::minmax_element() to find the minimum and maximum elements in a range or a container.

  1. std::minmax():
  • std::minmax() is used to find both the minimum and maximum elements in a given range or container.
C++
 #include <iostream>
 #include <algorithm>

 int main() {
     int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
     auto result = std::minmax_element(std::begin(arr), std::end(arr));

     std::cout << "Minimum: " << *result.first << std::endl;
     std::cout << "Maximum: " << *result.second << std::endl;

     return 0;
 }

In this example, std::minmax_element() returns a pair of iterators pointing to the minimum and maximum elements in the range. You can access the values using result.first and result.second.

  1. std::minmax_element():
  • std::minmax_element() is used to find the iterators pointing to the minimum and maximum elements in a given range or container.
C++
 #include <iostream>
 #include <algorithm>
 #include <vector>

 int main() {
     std::vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
     auto result = std::minmax_element(numbers.begin(), numbers.end());

     std::cout << "Minimum: " << *result.first << std::endl;
     std::cout << "Maximum: " << *result.second << std::endl;

     return 0;
 }

This example uses a std::vector, but you can use these functions with other containers as well.

Both std::minmax() and std::minmax_element() provide a convenient way to find the minimum and maximum values in a range without having to write custom loops. They are part of the C++ Standard Library and are efficient for most use cases.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS