Use multimap to Create Associative Containers with Duplicate Keys

Use multimap to Create Associative Containers with Duplicate Keys

n a previous column, I discussed the Standard Library’s map associative container. But this was only one half the story. The Standard Library also defines a multimap container, which is similar to map except that it allows duplicate keys. This property makes multimap more useful than it seems at first: think of a phone book in which the same person may have two or more phone numbers, a file system in which multiple symbolic links are mapped to the same physical file, or to a DNS server that maps several URLs to the same IP address. In such cases, you’d want to do something like this:

//note: pseudo codemultimap  phonebook;phonebook.insert("Harry","8225687"); //homephonebook.insert("Harry","555123123"); //workphonebook.insert("Harry"," 2532532532"); //mobile

The ability to store duplicate keys in multimap heavily affects its interface and usage.


How to create an associative container with non-unique keys?


Use the multimap container defined in the

library.

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-codestring 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 #include multimap  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  value_type;iterator  insert(const value_type&); // #1 multimappair  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 , where the bool value indicates whether the insertion was successful.

Finding a Single Value
multimap, like map, has two overloaded versions of the find() member function:

iterator find(const key_type& k);const_iterator find(const key_type& k) const;

find(k) returns an iterator to the first pair that matches the key k. This means it’s mostly useful when you want to check whether there is at least one value associated with the key or when you need only the first match. For example:

typedef multimap  mmss;void func(const mmss & dns){ mmss::const_iterator cit=dns.find("213.108.96.7"); if (cit != dns.end())  cout <<"213.108.96.7 found" <

Handling Multiple Associated Values
The count(k) member function returns the number of values associated with a given key. The following example reports how many values are associated with the key 213.108.96.7:

cout<

To access multiple values in a multimap, use the equal_range(), lower_bound() and upper_bound() member functions:

  • equal_range(k): This function finds all of the values associated with the key k. This function returns a pair of iterators that mark the beginning and the end of the range. The following example displays all the values associated with the key 213.108.96.7:
    typedef multimap ::const_iterator CIT; typedef pair Range;Range range=dns.equal_range("213.108.96.7");for(CIT i=range.first; i!=range.second; ++i) cout << i->second << endl; //output: cpluspluszone.com                            //        cppzone.com
  • lower_bound() and upper_bound(): lower_bound(k) finds the first value associated with the key k, and upper_bound(k) finds the first element whose key is greater than k. The following example uses upper_bound() to locate the first element whose key is greater than 213.108.96.7. As usual, when the key is of type string a lexicographical comparison takes place:
    dns.insert(make_pair("219.108.96.70",                      "pythonzone.com"));CIT cit=dns.upper_bound("213.108.96.7");if (cit!=dns.end()) //found anything? cout<second<

    If you wish to display all the subsequent values, use a loop like this:

    //insert multiple values with the same keydns.insert(make_pair("219.108.96.70",                     "pythonzone.com"));dns.insert(make_pair("219.108.96.70",                     "python-zone.com"));//get an iterator to the first valueCIT cit=dns.upper_bound("213.108.96.7");//output: pythonzone.com python-zone.com while(cit!=dns.end()){ cout<second<

Concept Mapping
Although map and multimap have similar interfaces, the crucial difference between the two, with respect to duplicate keys, entails different design and usage. In addition, you should be aware of the subtle differences between the insert() member function of each container.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap