// Oldham, Jeffrey D. // 2000 Mar 15 // CS3352 // Histogram Using Maps for Integral Data // This program reads integral data from the standard input. When // finished, it prints out each element and the number of times each // element was seen. For example, // 0 34 // 1 23 // 2 4 // 3 1 // Implementation // Data is stored in a map, which is a class in the Standard Template // Library (http://www.sgi.com/Technology/STL/). Conceptually, a map // is a collection of pairs (key, value), sorted according to keys. // We use a map map, i.e., it contains pairs // of objects with type "inputType" and "unsigned int". "inputType" // represents the type of the input data, e.g., int, string, double. // "unsigned int" represents the number of occurrences of a particular // item. typedef int inputType; // type of input data // Change this if necessary. #include #include #include // has EXIT_SUCCESS #include // has pair #include // has for_each #include // helper printing an element and its count class printer { public: printer(ostream& o, const inputType cnt) : out(o), count(cnt) {} void operator()(const pair & p) { out << p.first << '\t' << p.second/count << endl; } private: ostream & out; const double count; }; int main(void) { // Read the data. unsigned long count = 0; map histogramMap; inputType i; inputType mx = INT_MIN; while (cin >> i) { ++histogramMap[i]; // increase element i's count ++count; mx = max(mx, i); } // Print the results. for (inputType i = 0; i <= mx; ++i) cout << i << '\t' << histogramMap[i] << endl; // TMP for_each(histogramMap.begin(), histogramMap.end(), printer(cout,count)); return EXIT_SUCCESS; }