1: //stable_sort2a.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: }
37: int main()
38: {
39: cout << "\nThis program illustrates the use of the STL stable_sort() "
40: "algorithm (extended\nversion) to sort a vector of integers, when "
41: "a first integer comes before a\nsecond if and only if the first "
42: "has a smaller digit sum than the second."
43:
44: "\n\nThe sort is stable, in that duplicate values retain their "
45: "original order."
46:
47: "\n\nAn interesting exercise is to change the call to "
48: "stable_sort() to a call\nto sort() and observe "
49: "the difference in output, if any.";
50: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
52: int a[] = {17, 12, 14, 111, 19, 23, 15, 61, 20, 81, 11, 21, 41, 34};
53: vector<int> v(a, a+14);
55: cout << "\nHere are the original contents of the vector:\n";
56: for (vector<int>::size_type i=0; i<v.size(); i++)
57: cout << v.at(i) << " ";;
58: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
60: stable_sort(v.begin(), v.end(), hasSmallerDigitSum);
62: cout << "\nAnd here the sorted contents of the vector:\n";
63: for (vector<int>::size_type i=0; i<v.size(); i++)
64: cout << v.at(i) << " ";;
65: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
66: }