1: //set_difference2a.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: "set_difference() algorithm\n(extended version) to find the " 40: "values that are in a first vector of integers\nbut not in a " 41: "second vector of integers, and write them out to a third " 42: "vector\nof integers. In this case the vectors are ordered " 43: "in the sense that one\ninteger comes before " 44: "another if and only if it has a smaller 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 but not in v2, " 73: "and\nwrite them out to v3, starting at the beginning of v3."; 74: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 76: vector<int>::iterator p; 77: p = set_difference(v1.begin(), v1.end(), 78: v2.begin(), v2.end(), v3.begin(), hasSmallerDigitSum); 80: cout << "\nHere are the revised contents of v3:\n"; 81: for (vector<int>::size_type i=0; i<v3.size(); i++) 82: cout << v3.at(i) << " "; 83: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 85: cout << "\nThe iterator returned by the algorithm is pointing at " 86: "the value " << *p << "."; 87: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 88: }