1: //vector_e.cpp
3: #include <iostream>
4: #include <vector>
5: #include <algorithm>
6: #include <functional>
7: using namespace std;
9: bool isOdd
10: (
11: int n //in
12: )
13: /**<
14: Determine if an input integer is odd.
15: @return true if the input integer is odd, and otherwise false.
16: @param n An integer.
17: @pre n contains a non-negative integer.
18: @post Returns true if n is odd, otherwise false.
19: */
20: {
21: return n%2 == 1;
22: }
24: int halfOf
25: (
26: int n //in
27: )
28: /**<
29: Find the value of an input integer divided by 2 (integer division).
30: @return The integer value of the input integer divided by 2.
31: @param n An integer.
32: @pre n contains a non-negative integer.
33: @post No side effects.
34: */
35: {
36: return n/2;
37: }
39: void Display
40: (
41: int n //in
42: )
43: /**<
44: Display an input integer and a following blank space.
45: @return void
46: @param n An integer.
47: @pre n contains a non-negative integer.
48: @post The value of the input integer has been displayed,
49: followed by a single blank space.
50: */
51: {
52: cout << n << " ";
53: }
56: int main()
57: {
58: cout << "\nThis program illustrates the use of the algorithms "
59: "count_if(), for_each(), and\ntransform() (from <algorithm>) "
60: "and also shows the use of a programmer-defined\n\"predicate "
61: "function\", as well as the built-in function object "
62: "negate<int>()\n(from <functional>).";
63: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
65: int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
66: vector<int> v(a, a+10);
68: cout << "\nContents of vector v, displayed using for_each() "
69: "\nand a programmer-defined Display() function:\n";
70: for_each(v.begin(), v.end(), Display);
71: //for_each() returns Display, which we ignore.
72: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
75: //Note the use of a programmer-defined "predicate" with the
76: //count_if algorithm (count_if returns a value of type size_t):
77: cout << "\nUsing a programmer-defined predicate function and "
78: "count_if(),\nwe find the number of odd integers in the vector: "
79: << (int)(count_if(v.begin(), v.end(), isOdd)) << endl;
80: cout << "Press Enter to continue ... "; cin.ignore(80, '\n');
82: cout << "\nNext we divide all values by 2, using a "
83: "programmer-defined function\nfor integer division, "
84: "combined with transform():\n";
85: transform(v.begin(), v.end(), v.begin(), halfOf);
86: //transform() returns an iterator, which we ignore.
87: for_each(v.begin(), v.end(), Display);
88: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
90: cout << "\nFinally, we negate the current values, again using "
91: "\ntransform but this time with a built-in function object:\n";
92: transform(v.begin(), v.end(), v.begin(), negate<int>());
93: for_each(v.begin(), v.end(), Display);
94: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
95: }