Using function templates to get the max and min value in an array : array algorithms « STL Introduction « C++ Tutorial






#include <iostream>
using std::cout;
using std::endl;


template<class T> T max(const T* data, int size) {
    T result = data[0];
    for(int i = 1 ; i < size ; i++)
      if(result < data[i])
        result = data[i];
    return result;
  }

template<class T> T min(const T* data, int size) {
    T result = data[0];
    for(int i = 1 ; i < size ; i++)
      if(result > data[i])
        result = data[i];
    return result;
  }



int main() {
  double data[] = {1.5, 4.6, 3.1, 1.1, 3.8, 2.1};
  int numbers[] = {2, 22, 4, 6, 122, 12, 1, 45};

  const int dataSize = sizeof data/sizeof data[0];
  cout << "Minimum double is " << min(data, dataSize) << endl; 
  cout << "Maximum double is " << max(data, dataSize) << endl; 

  const int numbersSize = sizeof numbers/sizeof numbers[0];
  cout << "Minimum integer is " << min(numbers, numbersSize) << endl; 
  cout << "Maximum integer is " << max(numbers, numbersSize) << endl;

  return 0;
}
Minimum double is 1.1
Maximum double is 4.6
Minimum integer is 1
Maximum integer is 122








14.1.array algorithms
14.1.1.Using the STL generic reverse algorithm with an array
14.1.2.Using reverse_copy to copy the array reversely
14.1.3.Use random_shuffle algorithms with array
14.1.4.Illustrating the generic inner_product algorithm with predicate
14.1.5.Illustrating the generic adjacent_difference algorithm
14.1.6.Illustrating the generic partial_sum algorithm
14.1.7.Use the generic partition algorithms: Partition array1, putting numbers greater than 4 first, followed by those less than or equal to 4
14.1.8.Using function templates to get the max and min value in an array