These functions are found in the #include <algorithm> library. In this document, let T represent any type name.
These are functions that find the maximum and minimum of a given set of values, and there are two approaches:
We will describe both approaches here as well as a related function: clamp(...).
The first two functions return the minimum and maximum of the two arguments, respectively; while the third returns a std::pair where first public member variable is assigned the minimum of the two, and second is assigned the minimum of the two; for example:
auto result{ std::minmax( 53, 32 ) }; std::cout << result.first << std::endl; // prints 32 std::cout << result.second << std::endl; // prints 53
All three of these functions allow for a third optional argument that is of type bool predicate( T lhs, T rhs ) that returns true if the lhs argument is less than the rhs.
All three of these functions also allow for the first two arguments to be replaced by an "initializer list" containing at least one entry; so for example
int a{ 32 }; // 'a' could be assigned any value... auto result{ std::minmax( {0, a, 255} ) }; std::cout << result.first << std::endl; std::cout << result.second << std::endl;
This would print the minimum of a and 0 and the maximum of a and 255.
The first two functions return an iterator that refers to the minimum or maximum entries in the range (returning itr_last if the range is empty), respectively. The third returns a std::pair of iterators, first being assigned an iterator referring to the minimum entry, and second to the maximum entry, and both begin assigned itr_last if the range is empty.
An implementation of the third would be as follows:
if ( itr_first == itr_last ) { return itr_last; } else { auto min_itr{ itr_first }; auto max_itr{ itr_first }; auto itr{ itr_first + 1 }; while ( itr != itr_last ) { if ( *itr < *min_itr ) { min_itr = itr; } else if ( *itr > *max_itr ) { max_itr = itr; } } return std::make_pair( min_itr, max_itr ); }
All three of these functions allow for a third optional argument that is of type bool predicate( T lhs, T rhs ) that returns true if the lhs argument is less than the rhs.
This was introduced in C++ 2017, and returns low if value is less than low, high if value is greater than high, and value otherwise.
<humor>You can guess what happens if low > high.</humor>
Like the above functions, this function, too, can take a fourth argument bool predicate( T lhs, T rhs ).
You can view examples at replit.com.