// B7.cpp - compute the average of the values of a vector, list, or set. #pragma warning(disable : 4786) #include #include #include #include using namespace std; ///////////////////////////////////////////////////////////////////// // The function below will fail to compile if the type container // does not provide every one of the container operations used in // the body of the function. These are: // - declare a const_iterator type // - declare a value_type type // - provide an assignment operator accepting a numeric value of 0 // - provide member functions begin() and end(), each returning // an iterator on the container // - provide a size() function, returning a numeric value comparable // to the numeric value 0 // For correct operation the value_type type must provide a correct // copy constructor or have correct compiler generated copy semantics, // support initialization with zero, and provide operator+=(...). template container::value_type average(const container &con) { container::const_iterator it; container::value_type sum = 0; for(it = con.begin(); it != con.end(); it++) sum += *it; if(con.size() > 0) return (sum/con.size()); return 0; } ////// end of complete answer ///////////////////////////////////////// void main() { double array[] = { -1.5, 0.5, 1.5, 2.5, 3.5 }; int size = sizeof(array)/sizeof(double); vector vd(&array[0], &array[size]); double vectorAvg = average(vd); cout << "\n average of vector is: " << vectorAvg; list ld(&array[0], &array[size]); double listAvg = average(ld); cout << "\n average of list is: " << listAvg; set sd(&array[0], &array[size]); double setAvg = average(sd); cout << "\n average of set is: " << setAvg; cout << "\n\n"; }