Mega Code Archive

 
Categories / C++ Tutorial / STL Algorithms Non Modifying Sequence Operations
 

Using for_each to Display the Contents of a Collection

#include <algorithm> #include <iostream> #include <vector> #include <string> using namespace std; template <typename elementType> class DisplayCounter{ private:     int m_nCount; public:     DisplayCounter (){         m_nCount = 0;     }     void operator () (const elementType& element) {         ++ m_nCount;         cout << element << ' ';     }     int GetCount(){         return m_nCount;     } }; int main (){     vector <int> v;     for (int nCount = 0; nCount < 10; ++ nCount)         v.push_back (nCount);     DisplayCounter<int> mIntResult = for_each ( v.begin (), v.end(), DisplayCounter<int> () );     cout << mIntResult.GetCount () << endl;     string str ("this is a test");     cout << str << endl << endl;     DisplayCounter<char> mCharResult = for_each (str.begin(), str.end(),DisplayCounter<char> () );     cout << mCharResult.GetCount () << endl;     return 0; }