#include #include #include using std::map; using std::cout; using std::endl; typedef std::string Word; int main() { Word w1 = "Apple", w2 = "Peach", w3 = "Banana", w4 = "Orange"; map< Word, int > m; // to add a "pair" to a map use the make_pair function along // with the map insert member function: m.insert( make_pair( w1, 1 ) ); m.insert( make_pair( w4, 4 ) ); m.insert( make_pair( w2, 2 ) ); m.insert( make_pair( w3, 3 ) ); // be careful and make sure that the arguments you pass to make_pair // are of the same type that the map contains - in this case // the first item of the pair is the KEY (aka index) that will be used // to find the second item of the pair (the data value) // you can then treat the map like an array and use the KEY to find // the data value (aka element) that is paired (associated) with that key cout << m[ "Apple" ] << endl; // should output 1 cout << m[ "Peach" ] << endl; // should output 2 cout << m[ "Banana" ] << endl; // should output 3 cout << m[ w4 ] << endl; // should output 4 m[ "Orange" ] = 100; // m[ KEY ] returns the item (by reference) paired // with that KEY and in this case modifies it. cout << m[ w4 ] << endl; // should output 100 m[ w4 ] = 4; cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << endl; // using an iterator on a map: // m.begin() returns an iterator to the first element of the map IN // SORTED ORDER! // m.end() returns an iterator to the element AFTER the last one // in the map // // also the iterator *points* to a special object a first and a second // field which can be accessed as below, the first field is the PAIR key // and the second field is the PAIR value. // // the way that a map works internally is that it creates a BST to // store the items "sorted" by their KEY - the Key type used must // support the < and == operators otherwise it won't compile map< Word, int >::const_iterator i; for ( i = m.begin(); i != m.end(); i++ ) cout << i->first << " " << i->second << endl; // prints the key and value pair // the above for loop will print out the fruit in alphabetic order cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << endl; cout << "The size of m is: " << m.size() << endl; // should be 4 cout << " and thus m is obviously"; if ( m.empty() ) cout << " empty." << endl; else cout << " not empty." << endl; m.clear(); // removes all of the elements of the map cout << endl << "The size of m is: " << m.size() << endl; cout << " and thus m is obviously"; if ( m.empty() ) cout << " empty." << endl; else cout << " not empty." << endl; m[ "FOO" ] = 3; // amazingly (and dangerously) it creates a pair // if the KEY doesn't exist cout << endl << "The size of m is: " << m.size() << endl; cout << " and thus m is obviously"; if ( m.empty() ) cout << " empty." << endl; else cout << " not empty." << endl; cout << endl << endl; return 0; }