00 /*
01     An exmple of a functor object as well as type conversion operators
02     Author: Simonas Saltenis
03 */
04 #include <algorithm>
05 #include <vector>
06 #include <iostream>
07 
08 using namespace std;
09 
10 class Counter
11 {
12 private:
13     int   what;
14     int&  counter;
15 
16 public:
17     Counter(int value, int& cnt): what{value}, counter{cnt} {}
18 
19     operator int() const { return counter; }   // note: no return type!
20 
21     void operator() (int item)
22     {
23         if (item == what) counter++;
24     }
25 };
26 
27 int main()
28 {
29     vector<int> data {1, 3, 8, 1, 8, 8, 9, 8};
30 
31 
32     int     cnt8 = 0;
33     Counter cnt(8, cnt8);
34     for_each (data.begin(), data.end(), cnt);  // count number of eights
35 
36     int cnt1  = 0;
37     for_each (data.begin(), data.end(), [&cnt1](int item){ if (item == 1) cnt1++; });  // count number of ones
38 
39     int diff = cnt - cnt1;   // Implicit conversion to int.
40     cout << diff << " more eights than ones" << endl;
41     return 0;
42 }
43