Ray's playground

 

STL Containers & Iterators part1(Chapter 4 of Thinking in C++ Vol 2)

code
 1 #include <iostream>
 2 #include <vector>
 3 #include <iterator>
 4 using namespace std;
 5 
 6 template<class Cont, class PtrMemFun>
 7 void apply(Cont& c, PtrMemFun f)
 8 {
 9     typename Cont::iterator it = c.begin();
10     while(it != c.end())
11     {
12         ((*it).*f)();
13         it++;
14     }
15 }
16 
17 class Z
18 {
19     int i;
20 public:
21     Z(int ii) : i(ii) {}
22     void g() { i++; }
23     friend ostream& operator<<(ostream& os, const Z& z)
24     {
25         return os << z.i;
26     }
27 };
28 
29 int main()
30 {
31     ostream_iterator<Z> out(cout, " ");
32     vector<Z> vz;
33     for(int i=0; i<10; i++)
34     {
35         vz.push_back(Z(i));
36     }
37     copy(vz.begin(), vz.end(), out);
38     cout << endl;
39     apply(vz, &Z::g);
40     copy(vz.begin(), vz.end(), out);
41     cin.get();
42 }

 

posted on 2011-01-08 22:17  Ray Z  阅读(223)  评论(0编辑  收藏  举报

导航