1: //set_union2a.cpp
3: #include <iostream>
4: #include <vector>
5: #include <algorithm>
6: using namespace std;
8: /**
9: Tests if one integer has a smaller digit sum than another.
10: Pre:\n i1 and i2 have been initialized and i1, i2 are both > 0.
11: Post:\n Returns true if sum of the digits in i1 is < sum of digits
12: in i2, and otherwise returns false.
13: */
14: bool hasSmallerDigitSum
15: (
16: int i1, //in
17: int i2 //in
18: )
19: {
20: int digitSum1 = 0;
21: while (i1 != 0)
22: {
23: digitSum1 += i1 % 10;
24: i1 /= 10;
25: }
27: int digitSum2 = 0;
28: while (i2 != 0)
29: {
30: digitSum2 += i2 % 10;
31: i2 /= 10;
32: }
33: return digitSum1 < digitSum2;
34: }
36: int main()
37: {
38: cout << "\nThis program illustrates the use of the STL set_union() "
39: "algorithm (extended\nversion) to find the values that are in a "
40: "first vector of integers or in a\nsecond vector of integers (or "
41: "in both), and write them out to a third vector\nof integers. "
42: "In this case the vectors are ordered in the sense that one "
43: "\ninteger comes before another if and only if it has a smaller "
44: "digit sum.";
45: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
47: int a1[] = {11, 12, 12, 12, 12, 13, 14, 15};
48: vector<int> v1(a1, a1+8);
50: cout << "\nHere are the values in the vector v1:\n";
51: for (vector<int>::size_type i=0; i<v1.size(); i++)
52: cout << v1.at(i) << " ";
53: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
55: int a2[] = {2, 21, 21, 31, 31, 61, 71, 81};
56: vector<int> v2(a2, a2+8);
58: cout << "\nHere are the values in the vector v2:\n";
59: for (vector<int>::size_type i=0; i<v2.size(); i++)
60: cout << v2.at(i) << " ";
61: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
63: int a3[] = {101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
64: 111, 112, 113, 114, 115};
65: vector<int> v3(a3, a3+15);
67: cout << "\nHere are the values in the vector v3:\n";
68: for (vector<int>::size_type i=0; i<v3.size(); i++)
69: cout << v3.at(i) << " ";
70: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
72: cout << "\nNow we find the values that are in v1 or in v2, "
73: "or in both,\nand write them out to v3, starting at the "
74: "beginning of v3.";
75: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
77: vector<int>::iterator p;
78: p = set_union(v1.begin(), v1.end(),
79: v2.begin(), v2.end(), v3.begin(), hasSmallerDigitSum);
81: cout << "\nHere are the revised contents of v3:\n";
82: for (vector<int>::size_type i=0; i<v3.size(); i++)
83: cout << v3.at(i) << " ";
84: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
86: cout << "\nThe iterator returned by the algorithm is pointing at "
87: "the value " << *p << ".";
88: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
89: }