Download presentation
Presentation is loading. Please wait.
Published byEleanor Potter Modified over 8 years ago
1
CPSC 252 Tables / Maps / Dictionaries Page 1 Tables, Maps and Dictionaries A table (or map or dictionary) is a collection of key/value pairs. In general the objects in a table have no fixed order and each object is accessed using the associated key. So, for example, we could have a table of drivers in BC, each object is a driver having a name, address, number of points for bad driving, etc. Each of these objects has an associated key – the corresponding driver’s license number. struct Driver { string name; string address; int points; int licenseNumber; };
2
CPSC 252 Tables / Maps / Dictionaries Page 2 In the example above, each object (driver) has a unique key (driver’s license number). In general it is important to understand that keys are not necessarily unique – it is possible that one key corresponds to many different objects (values). In the case where every object has a unique key, we refer to the table as a (one-to-one) map. If the keys are not unique so that more than one object is mapped onto the same key then we refer to the table as a many-to-one map or multimap.
3
CPSC 252 Tables / Maps / Dictionaries Page 3 Map Accessor (retrieving from a map) const object& operator[]( key ) const // given a key, the corresponding object is returned Note that: the return type is both const and a reference this is similar to [] in the IntVector class Usage example: cout << myTable[ key ]; // object corresponding to key is retrieved // from myTable and written to cout
4
CPSC 252 Tables / Maps / Dictionaries Page 4 Map Mutator (storing into a map) object& operator[]( key ); // used to associate a key with an object Note that: the return type is not const but is again a reference this is similar to [] in the IntVector class Usage example: myTable[ key ] = object; // inserts object into myTable and associates it with // the given key
5
CPSC 252 Tables / Maps / Dictionaries Page 5 Other necessary map methods bool empty( key ) const; // returns true if key is not in table; // otherwise false void erase( key ); // removes key and the corresponding object from // the table We will examine the implementation of maps (tables) later
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.