120 likes | 250 Views
Map and Multimap. ITK 169 Fall 2003. Map. A Standard Templated Library #include <map> Each value of a map is a pair. The pair is made up of a key and an element. The key may be of any type and it is what determines the ordering of the map.
E N D
Map and Multimap ITK 169 Fall 2003
Map • A Standard Templated Library • #include <map> • Each value of a map is a pair. • The pair is made up of a key and an element. • The key may be of any type and it is what determines the ordering of the map. • The element is the type of “things” stored in the map.
The key • In program 5, the key was a data member of the Player object and the object was never actually stored in the map. • map<string, int> playerIndex; • Here, we did not have a map of Players – rather we had a map of indexes. • The integer stored as the second element of the pair was the record number or location of this player in the file. • This is one way a map could be used.
Program 6 • In program 6 we might have decided to store our collection of Person pointers in a map instead of a list. map<string name, Person*> mymap; • Here name would have been a complete name – last first – not stored individually as in the actual object. • This would have automatically sorted the collection by name.
map Elements are Unique • In a map, the key must be a unique element. • Therefore if you have a map of students and you make their grade point the key, each student’s grade point would have to be unique (which is not likely to happen).
miltimap • A multimap is a map that allows elements with duplicate keys. • Still - #include <map>
map Methods • As with the other STL classes, the expected methods are available: • Constructors • size • empty • insert • erase • find • begin • end
pairs • The insert method takes a value that is a pair as its argument • A pair is defined pair<keyType, elementType> name(first, second); • So if we have a map defined as: map<string, double> students; • And we have a pair defined as: pair<string, double> aStu(“Smith, Bob”, 3.96); • We could insert the pairs using: students.insert(aStu);
Associative Array • In typical arrays, the index is always an integer. • In associative arrays, the index can be any type – int, double, string, or some user defined object • An assignment like students[“Brown, Mary”] = 3.5; • Inserts the pair <“Brown, Mary”, 3.5> into the students map.