Browse DevX
Sign up for e-mail newsletters from DevX


Use the <map> Library to Create Associative Containers

It's easy to associate values with an index when the index is an int, but what if you need to associate pairings of data of different types? The <map> library has an associative container that will come in handy in pairings of all data types. See how it works.




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

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 <map>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 <utility> //definition of pair
#include <string>

pair <string, string> prof_and_course("Jones", "Syntax");
pair <int, string> 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 <string,string>

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