Creating a custom algorithm based on template : Function Template « Function « C++






Creating a custom algorithm based on template

Creating a custom algorithm based on template
 

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;

template<class ForIter>
  void times2(ForIter start, ForIter end)
{
  while(start != end) {
    *start *= 2;
    start++;
  }
}

int main()
{
  int i;

  vector<int> vectorObject;

  for(i = 0; i <10; i++) 
     vectorObject.push_back(i);

  cout << "Initial Contents of vectorObject: ";
  for(i = 0; i <vectorObject.size(); i++)
    cout << vectorObject[ i ] << " ";
  cout << endl;

  times2(vectorObject.begin(), vectorObject.end());

  cout << "Contents of vectorObject doubled: ";
  for(i = 0; i <vectorObject.size(); i++)
    cout << vectorObject[ i ] << " ";
  cout << endl;

  list<float> lst;
  list<float>::iterator p;

  for(i = 0; i <5; i++) 
     lst.push_back((float)i*3.1416);

  cout << "Initial Contents of lst: ";
  for(p=lst.begin(); p!=lst.end(); p++)
    cout << *p << " ";
  cout << endl;

  times2(lst.begin(), lst.end());

  cout << "Contents of lst doubled: ";
  for(p=lst.begin(); p!=lst.end(); p++)
    cout << *p << " ";
  cout << endl;

  return 0;
}


           
         
  








Related examples in the same category

1.A generic mode finding function.A generic mode finding function.
2.Function template: swap valuesFunction template: swap values
3.Simple template function to accept two parametersSimple template function to accept two parameters
4.template function for find a valuetemplate function for find a value
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