C++/STL Algorithms Min Max/max
Call max() with special comparison function
<source lang="cpp">
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */
- include <algorithm>
- include <iostream>
using namespace std; /* function that compares two pointers by comparing the values to which they po int
*/
bool int_ptr_less (int* a, int* b) {
return *a < *b;
} int main() {
int x = 17; int y = 42; int* px = &x; int* py = &y; int* pmax; // call max() with special comparison function pmax = max (px, py, int_ptr_less); cout << *pmax; //...
}
/*
42
*/ </source>
Use max for char and integer
<source lang="cpp">
- include <iostream>
using std::cout; using std::endl;
- include <algorithm>
int main() {
cout << "\nThe maximum of "G" and "Z" is: " << std::max( "G", "Z" ); cout << "\nThe maximum of 12 and 7 is: " << std::max( 12, 7 ); cout << endl; return 0;
}
/*
The maximum of "G" and "Z" is: Z The maximum of 12 and 7 is: 12
*/ </source>
Using Custom Definitions of the Minimum and Maximum
<source lang="cpp">
- include <numeric>
- include <vector>
- include <iostream>
using namespace std; bool norm_less_than( const vector<double>& a,const vector<double>& b ); int main( ) {
const double data1[] = { 1.77, 3.33, -0.44 }; const double data2[] = { -1.99, -2.11, 4.33 }; vector<double> v1( data1, data1+sizeof( data1 )/sizeof( double ) ); vector<double> v2( data2, data2+sizeof( data2 )/sizeof( double ) ); const vector<double>& min_vector = min( v1, v2, norm_less_than ); const vector<double>& max_vector = max( v1, v2, norm_less_than );
} // returns true if the norm of a is < norm of b, false otherwise inline bool norm_less_than( const vector<double>& a,const vector<double>& b ) {
return inner_product( a.begin(), a.end(), a.begin(), 0.0 ) < inner_product( b.begin(), b.end(), b.begin(), 0.0 );
}
</source>