Maps
Data Structures and Abstractions
MAPS
Lecture 20
*
Note 1
When you compile some STL code in VC++ you might get a warning: [1]
ICT283\Code\Sets\SetDifference.cpp(59) : warning C4786: ‘std::pair,std::allocator>::_Kfn,std::less,std::allocator >::const_iterator,std::_Tree,std::allocator>::_Kfn,std::less,std::allocator >::const_iterator>’ : identifier was truncated to ‘255’ characters in the debug information
This is the only warning you can ignore completely (a debug identifier)
If it really annoys you, then add the following code before the includes in the file that is generating the warning:
#pragma warning (disable : 4786)
Do not disable any other warning!!
1
Not likely with these days. Might happen in older versions of VC++
*
Note 2
If you get an error message such as:
ICT283\Code\Map\Map.cpp(57) : error C2440: ‘initializing’ : cannot convert from ‘class std::_Tree,class std::allocator >,struct std::pair IntSet;
{
IntSet::iterator itr = aset.begin(); // itr can be used to modify
}
To solve it, use a const_iterator, instead of an iterator: [2]
void DoSomething (const IntSet &aset)
{
IntSet::const_iterator itr = aset.begin();
}
*
[1]
stuff like this is covered in the textbook – so please read the textbook.
See section on typedef const_iterator, Chapter on STL
Lecture notes wouldn’t contain everything in the textbook.
[2]
Note that aset is declared as a const reference.
Setting a normal iterator can’t guarantee the const declaration, so the compiler would not be happy as it
can’t enforce your design decision.
so you need a const iterator.
Maps
An association (pairing) is a connection between two things, for example the word “sanity” (key) is associated with the definition (value) “the state of having a normal healthy mind”*
A dictionary or map is then a collection of key-value associations [1].
The first part of the pair is often called a key.
The data in maps is inserted, deleted and found using the key. So key needs to be unique but value need not be. [2]
For example, if one had a map that was an English dictionary, then we would expect to be able to retrieve the definition of sanity using something like:
dictionary.GetDefinition (“sanity”);
or even
dictionary[“sanity”];
* Australian Dictionary, Collins, 2005
*
[1] Sometimes called Associative array
[2] Multimaps are used if keys are not unique.
Also see unordered_map (C++11). Hashing is used on the key for fast access. Operator[] is fast.
The STL Map
The STL map is a very nice template indeed.
The declaration requires two data types, the first being the key and the second being the data to be stored in association with the key. [1]
For example, consider a class taking a vote on who should be the class president. We want to associate names with an integer number of votes:
#include