Presenting the Problem
Unlike with
map, multimap may contain non-unique keys. This presents a problem: how can the overloaded subscript operator return multiple associated values for the same key? Consider the following example:
//note: pseudo-code
string phone=phonebook["Harry];
The
Standard Library designers resolved this issue by removing the subscript operator from
multimap. Consequently, insertion and retrieval of elements require different methods and error handling policies.
Insertion
Suppose you need to develop a DNS daemon (or service, in Windows parlance) that maps an IP address to a matching URL string. You know that in some cases, the same IP address is associated with two or more URLs, all of them pointing to the same site. In this case, you want to use multimap instead of map. You create a multimap like this:
#include <map>
#include <string>
multimap <string, string> DNS_daemon;
Instead of the
subscript operator, use the
insert() member function to insert elements.
insert() takes a
pair as its argument. The previous
10-Minute Solution demonstrated how to use the
make_pair() helper function to facilitate this task. You can use it
here as well:
DNS_daemon.insert(make_pair("213.108.96.7",
"cppzone.com"));
In the
insert() call above the string
213.108.96.7 serves as the key and
cppzone.com as its associated value. Here's a subsequent insertion of the same key but with a different associated value:
DNS_daemon.insert(make_pair("213.108.96.7",
"cppluspluszone.com"));
Consequently,
DNS_daemon contains two elements with the same key. Notice that the return values of
multimap::insert() and
map::insert() aren't the same:
typedef pair <const Key, T> value_type;
iterator
insert(const value_type&); // #1 multimap
pair <iterator, bool>
insert(const value_type&); // #2 map
The
multimap::insert() member function returns an iterator pointing to the newly inserted element (
multimap::insert() always succeeds).
map::insert() however returns
pair <iterator, bool>, where the
bool value indicates whether the insertion was successful.