Sams Teach Yourself C++ in 21 Days

(singke) #1
21: vInt[i] = i * 3;
22:
23: cout << “for_each()” << endl;
24: for_each(vInt.begin(), vInt.end(), DoPrint);
25: cout << endl;
26:
27: return 0;
28: }

for_each()
0 3 6 9 12
Note that all C++ standard algorithms are defined in <algorithm>, so it is
included on line 2 of the listing. Although most of the program should be easy
for you, one line, however, is worth reviewing. On line 24, the for_each()function is
called to go through each element in the vector vInt. For each element in the vector, it
invokes the DoPrintfunction object and passes the element to DoPrint.operator().
This results in the value of the element to be printed on the screen.

Mutating Sequence Operations
Mutating sequence operations perform operations that change the elements in a
sequence, including operations that fill or reorder collections. Listing 19.13 shows the
fill()algorithm.

LISTING19.13 A Mutating Sequence Algorithm
0: #include <iostream>
1: #include <vector>
2: #include <algorithm>
3: using namespace std;
4:
5: template<class T>
6: class Print
7: {
8: public:
9: void operator()(const T& t)
10: {
11: cout << t << “ “;
12: }
13: };
14:
15: int main()
16: {
17: Print<int> DoPrint;
18: vector<int> vInt(10);

OUTPUT


710 Day 19


LISTING19.12 continued

ANALYSIS
Free download pdf