1: //equal2a.cpp 3: #include <iostream> 4: #include <vector> 5: #include <algorithm> 6: using namespace std; 8: /** 9: Tests if two positive integers have the same digit sum. 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 digitSumsAreSame 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 equal() " 39: "algorithm (extended\nversion) to test whether the integers in a " 40: "range of integers in one vector\nmatch the integers in another " 41: "range in a different vector, in the sense of\nvalues in " 42: "corresponding positions having the same digit sum."; 43: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 45: int a1[] = {21, 13, 5}; 46: vector<int> v1(a1, a1+3); 47: cout << "\nHere are the contents of v1:\n"; 48: for (vector<int>::size_type i=0; i<v1.size(); i++) 49: cout << v1.at(i) << " "; 50: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 52: int a2[] = {21, 22, 23, 30, 31, 32}; 53: vector<int> v2(a2, a2+6); 54: cout << "\nHere are the contents of v2:\n"; 55: for (vector<int>::size_type i=0; i<v2.size(); i++) 56: cout << v2.at(i) << " "; 57: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 59: cout << "\nFirst we compare the sequence in v1 with the sequence " 60: "starting at the\nbeginning of v2, and ask whether they match."; 61: if (equal(v1.begin(), v1.end(), v2.begin(), digitSumsAreSame)) 62: cout << "\nYes, they match."; 63: else 64: cout << "\nNo, they don't match."; 65: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 67: cout << "\nThen we compare the sequence starting at the beginning " 68: "of v1 with the\nsequence starting at the second value of v2 " 69: "and ask whether they match."; 70: if (equal(v1.begin(), v1.end(), v2.begin()+1, digitSumsAreSame)) 71: cout << "\nYes, they match."; 72: else 73: cout << "\nNo, they don't match."; 74: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 76: cout << "\nFinally, we compare the sequence starting at the " 77: "beginning of v1 with the\nsequence starting at the second " 78: "value of v2 and ask whether they match."; 79: if (equal(v1.begin(), v1.end(), v2.begin()+3, digitSumsAreSame)) 80: cout << "\nYes, they match."; 81: else 82: cout << "\nNo, they don't match."; 83: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 84: }