Use a Function Object to Hold state : Function Template « Function « C++






Use a Function Object to Hold state

  
#include <algorithm>
#include <iostream>
#include <vector>
#include <list>

using namespace std;

template <typename elementType>
struct DisplayCounter
{
    int m_nCount;

    DisplayCounter ()
    {
        m_nCount = 0;
    }

    // Display the element, hold count!
    void operator () (const elementType& element)
    {
        ++ m_nCount;
        cout << element << ' ';
    }
};

int main ()
{
    vector <int> v;

    for (int nCount = 0; nCount < 10; ++ nCount)
        v.push_back (nCount);

    DisplayCounter <int> mResult;
    mResult = for_each ( v.begin (), v.end (), DisplayCounter <int> () );

    cout << "'" << mResult.m_nCount << "' elements were displayed!" << 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.Creating a custom algorithm based on templateCreating a custom algorithm based on template
6.find all template function
7.Using a Binary Function to Multiply Two Ranges
8.Making a Sequence of Random Numbers
9.write function object
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