1: //replace_copy_if1a.cpp
3: #include <iostream>
4: #include <vector>
5: #include <algorithm>
6: using namespace std;
8: /**
9: Determines if an integer is divisible by 3.
10: Pre:\n n contains an integer.
11: Post:\n Returns true if n is divisible by 3, and otherwise false.
12: */
13: bool isDivisibleByThree
14: (
15: int n //in
16: )
17: {
18: return (n%3 == 0);
19: }
21: int main()
22: {
23: cout << "\nThis program illustrates the use of the STL "
24: "replace_copy_if() algorithm to\ncopy all values from one "
25: "vector of integers to another and simultaneously\nreplace, "
26: "in the output, all values that satisfy a given predicate "
27: "with a\ngiven alternate value.";
28: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
30: int a1[] = {1, 2, 2, 3, 4, 5, 2, 3, 6, 7, 8, 9};
31: vector<int> v1(a1, a1+12);
33: cout << "\nHere are the values in the vector v1:\n";
34: for (vector<int>::size_type i=0; i<v1.size(); i++)
35: cout << v1.at(i) << " ";
36: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
38: int a2[] = {101, 102, 103, 104, 105, 106, 107,
39: 108, 109, 110, 111, 112, 113, 114};
40: vector<int> v2(a2, a2+14);
42: cout << "\nHere are the values in the vector v2:\n";
43: for (vector<int>::size_type i=0; i<v2.size(); i++)
44: cout << v2.at(i) << " ";
45: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
47: cout << "\nNow we copy all values from v1 to v2, starting at the "
48: "3rd value of v2,\nand simultaneously replace each value that's "
49: "divisble by 3 with 123.";
50: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
52: vector<int>::iterator p = replace_copy_if(v1.begin(), v1.end(),
53: v2.begin()+2, isDivisibleByThree, 123);
55: cout << "\nHere are the revised values in v2:\n";
56: for (vector<int>::size_type i=0; i<v2.size(); i++)
57: cout << v2.at(i) << " ";
58: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
60: cout << "\nThe iterator returned by the algorithm is pointing at ";
61: if (p == v2.end())
62: cout << "\nthe end of the vector v2.";
63: else
64: cout << "the value " << *p << ".";
65: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
66: }