containers/maps/map-3.cpp - Alternative version - using range-for for traveral of the map. | Lecture 6 - slide 12 : 40 Program 2 |
// 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 <iostream> #include <string> #include <map> using namespace std; void readitems(map<string, int> &m){ string word; int val; while (cin >> word >> val) m[word] += val; // Relies on the default map value initialization. } int main(){ map<string,int> 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; }