A generic mode finding function. : Function Template « Function « C++






A generic mode finding function.

A generic mode finding function.
 
#include <iostream>
#include <cstring>
using namespace std;


template <class X> X mode(X *data, int size)
{
  register int t, w;
  X md, oldmd;
  int count, oldcount;

  oldmd = 0;
  oldcount = 0;
  for(t=0; t<size; t++) {
    md = data[t];
    count = 1;
    for(w = t+1; w < size; w++) 
      if(md==data[w]) count++;
    if(count > oldcount) {
      oldmd = md;
      oldcount = count;
    }
  }
  return oldmd;
}

int main()
{
  int i[] = { 1, 2, 3, 4, 2, 3, 2, 2, 1, 5};
  char *p = "this is a test";

  cout << "mode of i: " << mode(i, 10) << endl;
  cout << "mode of p: " << mode(p, (int) strlen(p));

  return 0;
}


           
         
  








Related examples in the same category

1.Function template: swap valuesFunction template: swap values
2.Simple template function to accept two parametersSimple template function to accept two parameters
3.template function for find a valuetemplate function for find a value
4.Creating a custom algorithm based on templateCreating a custom algorithm based on template
5.find all template function
6.Using a Binary Function to Multiply Two Ranges
7.Making a Sequence of Random Numbers
8.write function object
9.Use a Function Object to Hold state
10.template function for bubble sort
11.template function for compacting the items
12.Template copy array function
13.function template for getting the max value
14.Overriding a template function.
15.Using Standard Parameters with Template Functions