As we know, both map and set can contain only a single instance of each key . The type multimap allow multiple instances of a key (1:n). In a phone directory, for example, some might wish to provide a separate listing for each phone number associated with an individual. The multimap type is defined in the same headers as the corresponding single-element versions: the map header .
[Note]
[1] The operations supported by multimap are the same as those on map, with one exception : multimap does not support subscripting . We cannot subscript a multimap because there may be more than one value associated with a given key.
[2] Because keys need not be unique, insert always adds an element .
[3] Finding elements in a multimap , we should note that maps store their elements in order, the multimap type does so as well . As a result, when a multimap has multiple instances of a given key, those instances will be adjacent elements within the container . It turns out that there are three strategies we might use to find and print all the elements by a given key. Each of these strategies relies on the face that we know that all the entries for a given key will be adjacent within the multimap . The strategies are as following.
(1) using find and count
(2) using lower_bound and upper_bound
(3) using equal_range (the best way )
[An example of multimap]
output:
[The usage of find and equal_range ]
[1]
typedef multimap<type,type>::iterator itType;
itType iter=m.find(key);
[2]
typedef multimap<type,type>::iterator itType;
pair<itType,itType> pos=m.equal_range(key);
output: