Generic sum method : Generic Algorithm « Generic « C++






Generic sum method

Generic sum method

#include <iostream>
using namespace std;

template <class X> X sum(X *data, int size)
{
  int i;
  X result = 0;

  for(i = 0; i <size; i++) result += data[ i ];

  return result;
}

int main()
{
  int i[] = {1, 2, 3, 4};
  double d[] = {1.1, 2.2, 3.3, 4.4};

  cout << sum(i, 4) << endl;
  cout << sum(d, 4) << endl;

  return 0;
}

           
       








Related examples in the same category

1.A generic bubble sort.A generic bubble sort.