1: //find_end2a.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 find_end() " 39: "algorithm (extended\nversion) to find the last occurrence of one " 40: "range of matching integer values\nin a vector within another " 41: "range of integer values, also in a vector, and\nwhere " 42: "corresponding values match if and only if they have the " 43: "same digit sum."; 44: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 46: int a1[] = {17, 21, 13, 5, 6, 7, 8, 12, 31, 14, 9, 10, 11}; 47: vector<int> v1(a1, a1+13); 48: cout << "\nHere are the contents of v1:\n"; 49: for (vector<int>::size_type i=0; i<v1.size(); i++) 50: cout << v1.at(i) << " "; 51: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 53: int a2[] = {21, 13, 5}; 54: vector<int> v2(a2, a2+3); 55: cout << "\nHere are the contents of v2:\n"; 56: for (vector<int>::size_type i=0; i<v2.size(); i++) 57: cout << v2.at(i) << " "; 58: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 60: vector<int>::iterator p; 62: p = find_end(v1.begin(), v1.end(), v2.begin(), v2.end(), 63: digitSumsAreSame); 64: if (p != v1.end()) 65: cout << "\nThe last instance of v2 in v1 begins at location " 66: << (int)(p-v1.begin()+1) << "."; 67: else 68: cout << "\nNo instance of v2 was found in v1."; 69: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 70: }