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