1: //lower_bound2a.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 lower_bound() "
39: "algorithm (extended\nversion) to find the lower bound "
40: "location of a given target value in a vector\nof integers "
41: "ordered in the sense that one integer precedes another if the "
42: "digit\nsum in the first is less than the digit sum in the second.";
43: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
45: int a[] = {21, 13, 31, 40, 5, 51, 25, 52, 70,
46: 8, 62, 71, 45, 54, 55, 82, 38, 56,
47: 65, 92, 39, 48, 75, 49, 59, 88};
48: vector<int> v(a, a+26);
49: cout << "\nHere are the contents of v:\n";
50: for (vector<int>::size_type i=0; i<v.size(); i++)
51: cout << v.at(i) << " ";
52: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
54: vector<int>::iterator lower;
56: lower = lower_bound(v.begin(), v.end(), 85, hasSmallerDigitSum);
57: if (lower != v.end())
58: cout << "\nLower bound of 85 in v = " << *lower;
59: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
61: lower = lower_bound(v.begin(), v.end(), 96, hasSmallerDigitSum);
62: if (lower != v.end())
63: cout << "\nLower bound of 96 in v = " << *lower;
64: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
66: lower = lower_bound(v.begin(), v.end(), 73, hasSmallerDigitSum);
67: if (lower != v.end())
68: cout << "\nLower bound of 73 in v = " << *lower;
69: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
71: lower = lower_bound(v.begin(), v.end(), 1, hasSmallerDigitSum);
72: if (lower != v.end())
73: cout << "\nLower bound of 1 in v = " << *lower;
74: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
76: lower = lower_bound(v.begin(), v.end(), 99, hasSmallerDigitSum);
77: if (lower != v.end())
78: cout << "\nLower bound of 99 in v = " << *lower;
79: cout << "\nNote that the lower bound location of 99 is "
80: "\nthe end (one-past-the-last) vector position.";
81: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
82: }