// Alternative version where the map is traversed with a range-for statement. // 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; // Accumulating total - and printing - via use of range-for: for(auto element: str_count){ // C++11 total += element.second; cout << element.first << "\t\t" << element.second << endl; } cout << "-------------------------\ntotal\t\t" << total << endl; }