//map2.cc illustrates use of map associating keys with values. // compare HashtableDemo.java A.Sedgwick 11/99 #include #include #include #include #include main() { map m; // keys and values are C-style strings m["Amy"] = "Biff"; // associate key Amy with value Biff // operator [] returns reference - behaves like put() when used as L-value //operator= copies "Biff" into slot established by operator[] method m["Jan"] = "Arthur"; m["Marg"]= "Bill"; cout << "Number of pairs in m now: " << m.size() << endl; cout << "Value associated with Marg: " << m["Marg"] << endl; // operator[] behaves like get when used as R-value cout << "Value associated with Jane: " << m["Jane"] << endl; // Note: this has effect of inserting null entry for Jane :( map::iterator it = m.begin(), stop = m.end(); for( ; it != stop; it++ ) { // operator ++ and operator * for iterator cout << (*it).first << "-"; // *it is a pair with key first cout << (*it).second << " " << endl; // and value second } vector keys; for( it = m.begin(); it != stop; it++ ) keys.push_back( it->first ); sort( keys.begin(), keys.end(), strcmp ); vector ::iterator i = keys.begin(), vstop = keys.end(); for( ; i != vstop; i++ ) { cout << *i << "-" << m[*i] << " "; } }