#include <algorithm> template< class T > const T& max( const T& a, const T& b ); template< class T, class Compare > const T& max( const T& a, const T& b, Compare comp );
Compares two elements and returns the greater one. One version of the function uses operator<
to compare the arguments, another uses the compare function p
.
a
, b
- arguments to be compared
comp
- comparison function which returns true
if the first parameter is less than the second
the greater of the given arguments
First version:
template<class T> const T& max(const T& a, const T& b) { return (a < b) ? b : a; }
Second version:
template<class T, class Compare> const T& max(const T& a, const T& b, Compare comp) { return (comp(a, b)) ? b : a; }
#include <algorithm> #include <iostream> int main() { std::cout << "larger of 1 and 9999: " << std::max(1, 9999) << std::endl; std::cout << "larger of 'a' and 'b': " << std::max('a', 'b') << std::endl; std::cout << "larger of 3.14159 and 2.71828: " << std::max(3.14159, 2.71828) << std::endl; return 0; }
Output:
larger of 1 and 9999: 9999 larger of 'a' and 'b': b larger of 3.14159 and 2.71828: 3.14159
constant