Use the <map> Library to Create Associative Containers

Use the <map> Library to Create Associative Containers

elational databases, scientific apps, and Web-based systems often need a vector-like container whose index can be of any type, not necessarily int. Such containers are known as associative containers or maps. For instance, a directory service application can store private names as indexes and phone numbers as their associated values:

directory["Harry"]=8225687;//insert "Harry" and his #iterator it=directory.find("Harry");//get Harry's phone #

Other applications of associative containers include DNS servers that map URLs to IP addresses, dictionaries, inventories, payrolls, and so on.


How do you implement associative containers whose index type isn’t confined to int?


Use the

library to create and manipulate associative containers.

Pairs and Maps
In a recent 10 Minute Solution, I presented the notion of a tuple, which is a collection of elements of different types. What I didn’t say is that the C++98 Standard Library already has a specialized tuple type called pair. A pair binds a key (known as the first element) with an associated value (known as the second element). For example:

#include  //definition of pair#include pair  prof_and_course("Jones", "Syntax");pair  symbolic_const (0, "false");

The Standard Library also defines a helper function that facilitates the creation of a pair type:

string prof;string course;make_pair(prof,course);//returns pair 

Step 1: Constructing and Populating a Map
Suppose you’re developing an address book that contains names and emails. The class template map defined in the header

is an associative container that uses a pair of types, the first of which is the index and the second the associated value.

We can use a map like this:

#include map  addresses;

To add an item to a map, use the subscript operator.

addresses["Paul W."]="[email protected]";

Here, the string Paul W. serves as the index or key, and [email protected]is its associated value. If the map already contains this key, the current associated value is replaced with the new associated value:

addresses["Paul W."]= "[email protected]"; //overrides "[email protected]"

Step 2: Searching
If you wish to check whether a certain element exists without inserting it, use the find() member function. find()has two overloaded versions:

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

As usual, a typedef can make the code less cumbersome:

typedef map ::const_iterator CIT;CIT cit=addresses.find("Paul W.");if (cit==addresses.end())  cout << "sorry, no such key" << endl;else  cout << cit->first << '	' << cit->second << endl;

The expressions cit->first and cit->second return the key and its associated value, respectively.

There is another way to test whether a certain pair is present without changing its associated value, namely, using the insert()member function:

// calls pair map::insert(const value_type& x);// the bool part reports whether the insertion succeededif (addresses.insert(make_pair("Paul W.", "[email protected]")).second== false){      // pair not inserted because the key already has a value      // original value left unchanged}

Step 3: Traversal
Let's look at a more realistic scenario. Suppose you're running a travel agency. Each agent gets a bonus for selling a deal. These bonuses are stored in a file as follows:

Bob 35Bob 90Jane 80.25Sue 100Jane 65.5

Your application has to sum up all these bonuses and print the total for each agent. First, create a map and read the data from the file:

map  bonuses;string agent;double bonus=0; ifstream bonusfile("bonuses.dat");if(!bonusfile){ //report the error and terminate}while (bonusfile >> agent >> bonus){ bonuses[agent]+=bonus;//accumulate bonuses per agent}

Believe it or not, that's all! Let's analyze this loop. After opening the data file, the while-loop reads each pair into the objects agent and bonus. Next, it inserts agent and bonus into the map. The trick here is that if the key (agent) already exists, the += operator adds the newly-read bonus to the current bonus stored in the map. This is possible because the expression

map[key] 

returns the value associated with key. This value is then added to the newly-read bonus when the overloaded operator += is invoked. Finally, the sum of these two values overrides the existing associated value in the map.

Luckily, when the map doesn't contain the sought-after key, the expression

map[key] 

returns a default-initialized T where Tis double in our example. A default-initialized double equals 0.

At this stage, the map contains pairs of agents and their combined bonus value. The following loop displays these pairs:

for(CIT p=bonuses.begin(); p!=bonuses.end(); ++p){ cout << p->first <<'	' << p->second <
Figure 1. Bonus Boys: The map displays the agents and the associated values that go with them.

The output is shown in Figure 1.

Hashed Associative Containers
The Standard Library doesn't provide a hashed associative containeryet. Such containers can improve performance significantly as they use a hashing algorithm to derive a short key from the original string index. However, many IDEs offer hashed containers as a non-standard extension. Fortunately, the new C++0X standard remedies this omission by adding a set of hashed containers and related algorithms to C++.

devx-admin

devx-admin

Share the Post:
Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic