// B2.1.cpp : Defines the entry point for the console application. // // Implement a function that accepts an STL container and computes the // average 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 #include using namespace std; template cont::value_type contAvg(const cont &c) { cont::const_iterator it; cont::value_type sum = 0; if(c.empty()) return sum; for(it=c.begin(); it!=c.end(); ++it) { sum += *it; } return (sum/c.size()); } int _tmain(int argc, _TCHAR* argv[]) { std::cout << "\n Exam B2 - Question #1 " << "\n =======================\n"; set ss; cout << "\n average of empty set contents = " << contAvg(ss); cout << "\n\n"; double darray[] = { 1.5, -13.4, 0.58, 53.7, -13 }; vector vec(&darray[0], &darray[5]); cout << "\n average of vector contents = " << contAvg(vec); cout << "\n\n"; int iarray[] = { 1, 2, 3, 4, 5 }; list lst(&iarray[0], &iarray[5]); cout << "\n average of list contents = " << contAvg(lst); cout << "\n\n"; return 0; }