
Module: Standard C++ Library Library: Algorithms
Function
Algorithm that returns the maximum of a pair of values
#include <algorithm>
namespace std {
template <class T>
const T& max(const T&, const T&);
template <class T, class Compare>
const T& max(const T&, const T&, Compare);
}
The max() algorithm determines and returns the maximum of a pair of values. In the first case, T must satisfy the requirements of LessThanComparable. In the second case, the optional argument Compare defines a binary function object that can be used in place of the default operator<().
max() returns the first argument when the arguments are equal.
//
// max.cpp
//
#include <algorithm> // for max, min
#include <functional> // for greater
#include <iostream> // for cout
int main ()
{
double d1 = 10.0, d2 = 20.0;
// Find minimum.
double val1 = std::min (d1, d2);
// The greater comparator returns the greater of
// the two values.
double val2 = std::min (d1, d2, std::greater<double>());
// Find minimum.
double val3 = std::max (d1, d2);
// The less comparator returns the smaller of
// the two values.
// Note that, like every comparison in the library, max is
// defined in terms of the < operator, so using less here
// is the same as using the max algorithm with a default
// comparator.
double val4 = std::max(d1, d2, std::less<double>());
std::cout << val1 << " " << val2 << " "
<< val3 << " " << val4 << std::endl;
return 0;
}
Program Output:
10 20 20 20
max_element(), min(), min_element()
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Sections 25.3.7 and 20.1.2
Copyright (c) 1994-2006 Rogue Wave Software, a Quovadx Division.
Licensed under the Apache License, Version 2.0.
Contact Rogue Wave about documentation or support issues. You can also seek help from other developers through the Apache stdcxx community (see below).