1: //nth_element2a.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 "
39: "nth_element() algorithm (extended\nversion) to partition "
40: "a vector of integers of size 12 around its 7th element. "
41: "\nThe ranges on either side of this value may or may not "
42: "be sorted, but the\nalgorithm does not guarantee this, "
43: "and you should not expect it. In this case\nthe order of "
44: "the elements is determined by one integer preceding another "
45: "if\nand only if it has a smaller digit sum. ";
46: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
48: int a[] = {92, 21, 53, 84, 46, 13, 41, 76, 45, 61, 11, 15};
49: vector<int> v(a, a+12);
50: cout << "\nHere are the initial contents of the vector:\n";
51: for (vector<int>::size_type i=0; i<v.size(); i++)
52: cout << v.at(i) << " ";
53: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
55: cout << "\nNow we make the following call:";
56: cout << "\nnth_element(v.begin(), v.begin()+6, v.end());";
57: nth_element(v.begin(), v.begin()+6, v.end(), hasSmallerDigitSum);
58: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
60: cout << "\nAnd here are the contents of the vector partitioned "
61: "around its 7th element:\n";
62: for (vector<int>::size_type i=0; i<v.size(); i++)
63: cout << v.at(i) << " ";
64: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
65: }