C++ Tutorial/STL Algorithms Min Max/min

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Call min() 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.
*/
  1. include <algorithm>
  2. 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* pmin;
   // call min() with special comparison function
   pmin = min (px, py, int_ptr_less);
   cout << *pmin;
   //...

}</source>

17

min

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <algorithm>

int main() {

  cout << "\nThe minimum of "G" and "Z" is: " << std::min( "G", "Z" );
  cout << "\nThe minimum of 12 and 7 is: " << std::min( 12, 7 );
  cout << endl; 
  return 0;

}</source>

The minimum of "G" and "Z" is: G
The minimum of 12 and 7 is: 7

Use max and min functions

<source lang="cpp">#include <algorithm>

  1. include <iostream>

using namespace std; int main(int argc, char** argv) {

 int x = 4, y = 5;
 cout << "x is " << x << " and y is " << y << endl;
 cout << "Max is " << max(x, y) << endl;
 cout << "Min is " << min(x, y) << endl;
 swap(x, y);
 cout << "x is " << x << " and y is " << y << endl;
 cout << "Max is " << max(x, y) << endl;
 cout << "Min is " << min(x, y) << endl;
 return (0);

}</source>