// A2.10.cpp : Defines the entry point for the console application. // // Implement a function that accepts an STL container and computes the // sum of its contents. Your function must be able to accept more than // one type of container, say either a list or a vector, but you are // required to show only that it is correct for a vector. #include "stdafx.h" #include #include #include #include using namespace std; template cont::value_type contSum(const cont &c) { cont::const_iterator it; // using fact that static memory is initialized to zero // since we can't say sum = 0 for strings static cont::value_type sum; for(it=c.begin(); it!=c.end(); ++it) { sum += *it; } return sum; } template V contSum2(const U &u) { U::const_iterator it; static V sum; for(it=u.begin(); it!=u.end(); ++it) sum += *it; return sum; } int _tmain(int argc, _TCHAR* argv[]) { std::cout << "\n Exam A2 - Question #10 " << "\n ========================\n"; double darray[] = { 1.5, -13.4, 0.58, 53.7, -13 }; vector vec(&darray[0], &darray[5]); cout << "\n sum of vector contents = " << contSum(vec); cout << "\n\n"; string sarray[] = { "John ", "Mary ", "Joseph ", "Ephram ", "Jennifer " }; list lst(&sarray[0], &sarray[5]); cout << "\n sum of list contents = " << contSum(lst); cout << "\n\n"; cout << "\n sum of vector contents = " << contSum2,double>(vec); cout << "\n\n"; cout << "\n sum of list contents = " << contSum2,string>(lst); cout << "\n\n"; return 0; }