Chapter 59. Boost.MinMax

Boost.MinMax provides an algorithm to find the minimum and the maximum of two values using only one function call, which is more efficient than calling std::min() and std::max().

Boost.MinMax is part of C++11. You find the algorithms from this Boost library in the header file algorithm if your development environment supports C++11.

Example 59.1. Using boost::minmax()

  1. #include <boost/algorithm/minmax.hpp>
  2. #include <boost/tuple/tuple.hpp>
  3. #include <iostream>
  4. int main()
  5. {
  6. int i = 2;
  7. int j = 1;
  8. boost::tuples::tuple<const int&, const int&> t = boost::minmax(i, j);
  9. std::cout << t.get<0>() << '\n';
  10. std::cout << t.get<1>() << '\n';
  11. }

boost::minmax() computes the minimum and maximum of two objects. While both std::min() and std::max() return only one value, boost::minmax() returns two values as a tuple. The first reference in the tuple points to the minimum and the second to the maximum. Example 59.1 writes 1 and 2 to the standard output stream.

boost::minmax() is defined in boost/algorithm/minmax.hpp.

Example 59.2. Using boost::minmax_element()

  1. #include <boost/algorithm/minmax_element.hpp>
  2. #include <array>
  3. #include <utility>
  4. #include <iostream>
  5. int main()
  6. {
  7. typedef std::array<int, 4> array;
  8. array a{{2, 3, 0, 1}};
  9. std::pair<array::iterator, array::iterator> p =
  10. boost::minmax_element(a.begin(), a.end());
  11. std::cout << *p.first << '\n';
  12. std::cout << *p.second << '\n';
  13. }

Just as the standard library offers algorithms to find the minimum and maximum values in a container, Boost.MinMax offers the same functionality with only one call to the function boost::minmax_element().

Unlike boost::minmax(), boost::minmax_element() returns a std::pair containing two iterators. The first iterator points to the minimum and the second points to the maximum. Thus, Example 59.2 writes 0 and 3 to the standard output stream.

boost::minmax_element() is defined in boost/algorithm/minmax_element.hpp.

Both boost::minmax() and boost::minmax_element() can be called with a third parameter that specifies how objects should be compared. Thus, these functions can be used like the algorithms from the standard library.