// A1.10.cpp : Defines the entry point for the console application. // // Implement a function that accepts an STL container and provides to // its client the maximum and minimum values in the container. 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. Under what circumstances will your // implementation fail to compile? #include "stdafx.h" #include #include #include using namespace std; //// answer ///////////////////////////////////////////////////////// template void MaxAndMin(cont &c, cont::value_type &max, cont::value_type &min) { if(c.size() == 0) return; cont::iterator it; max = min = *c.begin(); cont::value_type temp; for(it = c.begin(); it != c.end(); ++it) { temp = *it; if(temp > max) max = temp; if(temp < min) min = temp; } } ///////////////////////////////////////////////////////////////////// template void showCont(cont &c) { cout << "\n "; cont::iterator it; for(it=c.begin(); it!=c.end(); ++it) { cout << (*it) << " "; } cout << endl; } bool operator<(string &lhs, string &rhs) { return (strcmp(lhs.c_str(),rhs.c_str()) == -1); } bool operator>(string &lhs, string &rhs) { return (strcmp(lhs.c_str(),rhs.c_str()) == 1); } ostream& operator<<(ostream& out, string& s) { out << s.c_str(); return out; } // first argument won't compile // //template void MaxAndMin2(const C& cont, V& max, V& min) //{ // C::const_iterator it; // max = min = cont.begin(); // for(it = cont.begin(), it != cont.end(); ++it) // { // if(max < *it) max = *it; // if(min > *it) min = *it; // } //} template void MaxAndMin3(const C& cont, V& max, V& min) { C::const_iterator it; max = min = *cont.begin(); V temp; for(it = cont.begin(); it != cont.end(); ++it) { temp = *it; if(max < temp) max = *it; if(min > temp) min = *it; } } int _tmain(int argc, _TCHAR* argv[]) { std::cout << "\n Exam A1 - Question #10 " << "\n ========================\n"; double array[5] = { 3.3, -2.2, 15.8, 100.5, -33.0 }; vector vec(&array[0], &array[5]); showCont(vec); double max, min; MaxAndMin(vec, max, min); cout << "\n max = " << max << ", min = " << min << endl; string StrArray[5] = { "horse", "ardvarrk", "tiger", "mongoose", "eagle" }; list lst(&StrArray[0], &StrArray[5]); showCont(lst); string StrMax, StrMin; MaxAndMin(lst, StrMax, StrMin); cout << "\n StrMax = " << StrMax.c_str() << ", StrMin = " << StrMin.c_str(); cout << "\n\n"; MaxAndMin3,double>(vec,max,min); cout << "\n max = " << max << ", min = " << min << endl; MaxAndMin3,string>(lst,StrMax,StrMin); cout << "\n StrMax = " << StrMax << ", StrMin = " << StrMin << endl; cout << "\n\n"; return 0; }