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

Home
C++
1.Bitset
2.Class
3.Console
4.Data Structure
5.Data Type
6.Deque
7.Development
8.File
9.Function
10.Generic
11.Language
12.List
13.Map Multimap
14.Overload
15.Pointer
16.Qt
17.Queue Stack
18.Set Multiset
19.STL Algorithms Binary search
20.STL Algorithms Heap
21.STL Algorithms Helper
22.STL Algorithms Iterator
23.STL Algorithms Merge
24.STL Algorithms Min Max
25.STL Algorithms Modifying sequence operations
26.STL Algorithms Non modifying sequence operations
27.STL Algorithms Sorting
28.STL Basics
29.String
30.Valarray
31.Vector
C / ANSI-C
C Tutorial
C++ Tutorial
Visual C++ .NET
C++ » STL Basics » array algorithmsScreenshots 
Using function templates to get the max and min value in an array
 
 

#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 = ; 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 = ; i < size ; i++)
      if(result > data[i])
        result = data[i];
    return result;
  }



int main() {
  double data[] {1.54.63.11.13.82.1};
  int numbers[] {2224612212145};

  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

 */        
  
Related examples in the same category
1.Using the STL generic reverse algorithm with an array
2.Using reverse_copy to copy the array reversely
3.Use random_shuffle algorithms with array
4.Illustrating the generic inner_product algorithm with predicate
5.Illustrating the generic adjacent_difference algorithm
6.Illustrating the generic partial_sum algorithm
7.Use the generic partition algorithms: Partition array1, putting numbers greater than 4 first, followed by those less than or equal to 4
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.