// Reproduced from The C++ Programming Language, 3ed, page 483. // Read strings and counts from standard input, and keep track of the // sum for a particular string in the map. Also calculate the final total. #include #include #include using namespace std; void readitems(map &m){ string word; int val; while (cin >> word >> val) m[word] += val; // Relies on the default map value initialization. } int main(){ map str_count; // All values in the map are initialized to 0. readitems(str_count); int total = 0; using CI = map::const_iterator; // C++11 // Accumulating total - and printing - via use of const interator: for(CI it = str_count.begin(); it != str_count.end(); ++it){ pair element = *it; // Emphasizing that keys and values are grouped in a pair. total += element.second; cout << element.first << "\t\t" << element.second << endl; } cout << "-------------------------\ntotal\t\t" << total << endl; }