// ========================================================================== // $Id: stl_map.cpp,v 1.5 2017/11/25 00:27:06 jlang Exp $ // CSI2372 example Code for lecture 11 // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: jlang (Jochen Lang) // Email: jlang@site.uottawa.ca // ========================================================================== // $Log: stl_map.cpp,v $ // Revision 1.5 2017/11/25 00:27:06 jlang // Added copy. // // Revision 1.4 2015/11/16 16:07:58 jlang // Better comments. // // Revision 1.3 2015/11/16 15:52:39 jlang // Add C++11 features in dealing with map. // // Revision 1.2 2011/09/10 01:08:19 jlang // Updates F10 // // Revision 1.1 2006/11/08 01:41:35 jlang // added stl code for lecture 11 // // // ========================================================================== #include #include #include #include #include using std::cout; using std::endl; using std::string; using std::map; using std::make_pair; int main( int argc, char* argv[] ) { // map with string as a key and int as value map siMap{{"Smith, John", 31245}, {"Doe, Jane",245876}, {"Scott, Stephen",34411}}; // Add another entry siMap["Sobey, Anna"] = 89554; // Update value for existing key siMap["Doe, Jane"] = 2; // duplicate key - no insertion siMap.insert(make_pair("Doe, Jane", 1)); // insert pairs in other map - types must match map oMap; oMap.insert( siMap.begin(), siMap.end() ); // map ::iterator auto iter = oMap.find("Doe, Jane"); if ( iter != oMap.end() ) { cout << "Found: "; cout << iter->first << " val: " << iter->second << endl; oMap.erase( iter ); } cout << endl; cout << "Content of siMap: (printed with iterator)" << endl; // map::const_iterator for ( auto iter = siMap.cbegin(); iter != siMap.cend(); ++iter ) { cout << "Key: " << iter->first << endl; cout << "Value: " << iter->second << endl; } cout << endl; cout << "Content of siMap: (printed with range loop)" << endl; for (auto si:siMap) { cout << "Key: " << si.first << endl; cout << "Value: " << si.second << endl; } std::vector > siVec; siVec.resize(siMap.size()); std::copy( siMap.begin(), siMap.end(), siVec.begin()); cout << "Content of siVec: (printed with range loop)" << endl; for ( const auto& si:siVec ) { cout << "Key: " << si.first << endl; cout << "Value: " << si.second << endl; } cout << endl; return 0; }