/* ** $Id: maps.cc 861 2008-04-04 03:34:08Z phf $ ** ** Very brief introduction to std::map which is ** a very, very useful data structure to know about. ** ** You can think of maps as "general arrays" where ** integers (positions in arrays) are replaced by ** "any type" we want. So we can *index* the data ** structure with, for example, strings instead of ** integers. This often comes in very handy when we ** want to build more complex data structures, e.g. ** by using maps of maps. Neat stuff. :-) */ #include #include #include int main() { // We start by declaring a map instance. Note that we // have *two* type parameters: The first for the keys // to be used, the second for the values to be used. // Compared to arrays or vectors, where the keys are // always integers, keys can be just about anything // for maps. The only requirement for the key type // is that it supports a "<" ordering operation. std::map phonebook; // Inserting key-value pairs is done using the familiar // array notation (the map class overloads the operator // "[]" in various ways to make that possible). phonebook["Peter"] = 8710; phonebook["Joanne"] = 4117; phonebook["Scott"] = 5299; phonebook["Fidel"] = 0xCAFEBABE; phonebook["Harry"] = 0; phonebook["Sally"] = 1; // We can of course also use "[]" to get values back // out: std::cout << phonebook["Peter"] << std::endl; std::cout << phonebook["Fidel"] << std::endl; std::cout << "==========" << std::endl; // Note what happens when we try to access a key that // does not exist: std::cout << phonebook["Bla"] << std::endl; std::cout << "==========" << std::endl; // That's not completely satisfying of course, since // 0 could be a valid value itself. We can make sure // that something doesn't exist by using count(). std::cout << phonebook.count( "Peter" ) << std::endl; std::cout << phonebook.count( "Fidel" ) << std::endl; std::cout << phonebook.count( "Bla" ) << std::endl; std::cout << phonebook.count( "Dudel" ) << std::endl; std::cout << "==========" << std::endl; // But what the heck is wrong now? Why does "Bla" have // a count of 1 instead of 0? For some strange reason, // when you try to get an element that doesn't exist, // it will be inserted into the map as well with the // default value of the value type. Strange indeed. :-/ // Maps are structured as *pairs* of keys and values; // iterators on maps therefore return *pairs* that // can be "deconstructed" using "first" and "second" // accessors as follows: for (std::map::iterator i = phonebook.begin(); i != phonebook.end(); i++) { std::cout << "Key: " << i->first << " Value: " << i->second << std::endl; } // Let me point out how this could be used as part // of Assignment 8 to implement LearningHosts: // // std::map > crazy; // // I'll leave it at that, you can figure out the rest. // Don't worry... return 0; }