Browse DevX
Sign up for e-mail newsletters from DevX


Use multimap to Create Associative Containers with Duplicate Keys-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

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("", "cppzone.com"));

In the insert() call above the string 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("", "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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date