Abstract
For_each () is an algorithm with a few return values in STL. This example shows the special function for_each () and function object can retain state.
Introduction
The difference between a function object and a global function is not only that a function object can be merged into a dynamic state, but also that a State can be retained without using static state.
A simple requirement. If you want to print n numbers each time, you can print the sum of all iterator numbers, therefore, the function object must retain the State to know the number of characters that have been printed and the sum is counted.
Sample Code
1 /**/ /*
2 (C) oomusou 2007 Http://oomusou.cnblogs.com
3
4 Filename: genericalgo_for_each_state_returnvalue.cpp
5 Compiler: Visual C ++ 8.0/BCB 6.0/GCC 3.4.2/iso c ++
6 Description: Demo how to use for_each to return value and remain state.
7 Release: 05/13/2007 1.0
8 05/15/2007 2.0
9 */
10
11 # Include < Iostream >
12 # Include < Algorithm >
13 # Include < Vector >
14
15 Using Namespace STD;
16
17 Class Printelem {
18 Private :
19 Int _ N;
20 Int _ CNT;
21 Int _ Sum;
22
23 Public :
24 Printelem ( Int N = 5 ): _ N (n), _ CNT ( 0 ), _ Sum ( 0 ) {}
25
26 Void Operator ()( Int ELEM) {
27 ++ _ CNT;
28 _ Sum + = ELEM;
29
30 Cout < ELEM;
31
32 (_ CNT % _ N) ? Cout < " " : Cout < Endl;
33 }
34
35 Operator Int () {
36Return_ Sum;
37}
38 } ;
39
40 Int Main () {
41 Vector < Int > Ivec;
42
43 For ( Int I = 0 ; I ! = 20 ; ++ I)
44 Ivec. push_back (I );
45
46 Int Sum = For_each (ivec. Begin (), ivec. End (), printelem ( 5 ));
47
48 Cout < " Sum is " < Sum < Endl;
49 }
Results
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Sum is 190
17 rows
Private :
Int _ N;
Int _ CNT;
Int _ Sum;
_ N to set the number of text Jumpers
_ CNT statistics have been printed with several characters
_ Sum calculation result
29 rows
If (_ CNT % _ N)
Cout < ELEM < " " ;
Else
Cout < ELEM < Endl;
If n characters are printed each time, a line is printed.
35 rows
Operator Int () {
Return_ Sum;
}
In order to allow for_each () to restore the value, change operator int () so that the function object can restore the value.
46 rows
Int Sum = For_each (ivec. Begin (), ivec. End (), printelem ( 5 ));
In this way, for_each () can parse every n words of light and add the final result.
Conclusion
STL is really amazing. The above program can be converted to C # on a line !!