max_element |
Return the maximum element within a range.
Return an iterator positioned at
the maximum element in the range [ first, last ). The
first version uses operator< to perform the
comparisons, whereas the second version uses the binary function compare
.
#include <algorithm>
template< class ForwardIterator >
ForwardIterator max_element( ForwardIterator first, ForwardIterator last );
template< class ForwardIterator, class Compare >
ForwardIterator max_element
(
ForwardIterator first,
ForwardIterator last,
Compare compare
);
Time complexity is linear, as (
last - first )
comparisons are performed. Space complexity is constant.
#include <iostream>
#include <algorithm>
int numbers[ 6 ] = { 4, 10, 56, 11, -42, 19 };
void
main()
{
cout << *max_element( numbers, numbers + 6 ) << "\n";
}
56
#include <iostream>
#include <string.h>
#include <algorithm>
char* names[] = { "Brett", "Graham", "Jack", "Mike", "Todd" };
bool
str_compare( const char* a_, const char* b_ )
{
return ::strcmp( a_, b_ ) < 0 ? 1 : 0;
}
void
main()
{
const unsigned names_ct = sizeof( names )/sizeof( names[ 0 ] );
cout << *max_element( names, names + names_ct, str_compare ) << "\n";
}
Todd
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.