In this article, you will learn about “map” in the C++ programming language in detail. What is a map?  Why we use a map? How to create a map? How to use a map in C++? 

What is “MAP”?

The map is a library of standard template library (STL). Now you think that what is STL? 

STL is a collection of generic classes and functions. It is used to increase the reusability of code that is already developed. It saves time. STL has three main components:

  1. Containers: It stores the data and uses template classes.
  2. Algorithms: It is a set of rules and uses template functions.
  3. Iterators: It is an object that pointing to an element in the container. It handles just like a pointer.

Containers Properties:

  1. Associative: Elements stored in an associative array is pointed by their keys.
  2. Ordered: Elements are stored in a container in a strictly ordered fashion.
  3. Map: Each element has two parts. The first one is the key and the second one is mapped value through that key 
  4. Uniqueness: Each element has a unique key.
  5. Allocator-aware: It is responsible for dynamically storage allocation.

Let us deep-dive, into the map:

Map is an associative container/array that store the elements as a combination of key-value pairs (just like a dictionary). Keys are in ascending order (By default). 

Syntaxmap < key_datatype, value_datatype > map_name;

Here, key_datatype = datatype of key

value_datatype = datatypes of value corresponding to key 

map_name = Name of your map

For example:  map < string, int > student_map;

Here student_map is the name of the map, 

string and int are datatypes supported by map.

Concept of key-value:

  • Each element has stored a key value and a mapped value.
  • No two mapped value can have some key values.
  • Each key has a corresponding one value.

For example:

Roll NumName
11Dushyant
12Mahiraj
13Vipul

The generic syntax of the map:

template < class Key,                                    // map::key_type

           class T,                                      // map::mapped_type

           class Compare = less<Key>,                     // map::key_compare

           class Alloc = allocator<pair<const Key,T> >    // map::allocator_type

           > class map;

Why we use a map?

There are mainly two reasons for use map:

  1. Faster access of data: Fast access of values of elements through the key.
  2. No duplication of data: Every key is unique in the map so that duplication of data doesn’t exist.

Till now, we know that what is a map in C++ and the syntax of it. In this section we will learn how to create a map, initialization of map, accessing of map element. As we know the map store key-value pairs.

To use map in c++ we must have to include <map> in our program i.e.

#include <map>

Declaration of map in C++:

Syntax:

#include <iostream>

#include <map>

int main()

{

map<key_datatype, value_datatype> Map_name; // declare a map

return 0;

}

Initialization of map:

In this section, we will know how to initialize the map. For inserting the elements in the map first we have to declare a map.

i.e. map<key_datatype, value_datatype> Map_name;

we have three ways to insert elements in the map which are given below:

  1. Initialize a map at the declaration 

Syntax: map<key_datatype, value_datatype>map_name {{key1, value1}, {key2, value2}, .., {keyn,valuen}};

  1. Initialize a map using the insert function

Syntax: map<key_datatype, value_datatype>map_name;

map_name.insert(pair<key_datatype,  value_datatype>{key1, value1});

map_name.insert(pair<key_datatype,  value_datatype>{key2, value2});

  1. Initialize a map using square brackets syntax

Syntax: map<key_datatype, value_datatype>map_name;

map_name[key1] = value1;

map_name[key2] = value2;

Accessing an element of the map:

We can access and manipulates the elements of the map in two ways:

  1. Using square bracket

Syntax:

cout << map_name [key] << endl;

Explanation

We can access the value of any element in the map using its key as per the above syntax.

  1. Using at() function

Syntax:

cout << map_name.at(key) << endl;

Explanation:

We can access the value of any element in the map using at the () function which is an inbuilt function using the key as per the above syntax.

  1. Accessing element using iterator:

We have a problem accessing every element in the map because the map has no index so that is why we have the concept of an iterator.

As we studied in the above section iterators are treated as pointers that point elements in the container. So, for accessing a particular element in the map we use iterators. 

KeyValue
FirstSecond

Suppose,

Iterator can access key and value using the first and second keyword.

Syntax:

map<key_datatype,value_datatype> :: iterator iterator_name;

e.g. 

map<int, int> :: iterator i;

for(i=map_name.begin(); i!= map_name.end; i++)

cout<<(*i).first<< ” : ” << (*i).second<<endl;

}

Here in the above example,

Map_name.begin() return iterator to the beginning

map_name.end() return iterator to the end.

(*i).first => gives the key of the elements 

(*i).second => gives the values of the elements

This example prints all the elements in the map.

Let us take one example, suppose we want to store the mark of students where the key is the name of the student and the value is the mark.

The name has the string Datatype while the mark has an integer datatype.

Program:

#include<iostream>

#include<map> // for map

#include<string>   //For string operations

using namespace std;

int main(){

    map<string, int>student_map;   // Declaration of Map

    student_map [“Mahiraj”] = 87;  // Inserting elements

    student_map [“Vipul”] = 35;

    student_map [“Dushyant”] = 69;

    student_map.insert({{“Jaydeep”,77},{“Rajesh”,52}}); //

    map<string,int>::iterator itr;

    for(itr=student_map.begin(); itr!=student_map.end(); itr++)

        {

            cout<<(*itr).first<<” : “<<(*itr).second <<endl;

        }

}

Output:

Dushyant: 69

Jaydeep: 77

Mahiraj: 87

Rajesh: 52

Vipul: 35

Inbuilt function in “MAP” 

  1. begin() – it returns an iterator to the first element of map
  2. end() – it returns an iterator that follows the last element of the map.
  3. size() – it returns numbers of elements of the map.

An example of size is :

cout<<”the size is :”<<student_map.size();

This gives the size of the map

Output:

the size is:5

  1. max_size() – it returns maximum size of elements in map.

An example of max size is:

cout<<”the max-size is :”<<student_map.max_size();

This gives the maximum size of the map

Output:

The max-size is:97612893

  1. empty() – it checks that whether the map is empty or not and returns boolean (true/false).

The example of empty() is:

….

     cout<<”map is empty? :”<<student_map.empty();

This gives the Boolean value 0=false & 1=true.

Output:

map is empty? :0

  1. insert(key,value) – it insert new element in map.

map_name.insert({{key1,value1},{key2,value2}});

  1. erase (iterator location) – it removes the element which is specified at a location by the iterator.

The example of erase() is:

cout<<”Erase element:”<<student_map.erase (“Mahiraj”);

This gives the Boolean value 0=false & 1=true. 

Output:

Erase element: 1

  1. clear() – it deletes all the elements of the map.

student_map.clear();

  1. Find(loc) – it points to the element if element found at loc

cout<<”Erase element:”<<student_map.find (“Mahiraj”);

  1. swap() – it swaps the content of maps.

The full program of swap function is below:

#include <iostream>

#include <map>

#include <string> //For sting operations

using namespace std;

int main()

{

    map<string, int> kk,dd;

    kk[“Mahiraj”] = 87;

    kk[“Vipul”] = 35;

    kk[“Dushyant”] = 69;

    dd.insert({{“Jaydeep”, 77}, {“Rajesh”, 52}});

    kk.swap(dd);

    map<string, int>::iterator itr;

  cout<<“the kk map is :”;

    for (itr = kk.begin(); itr != kk.end(); itr++)

    {

        cout << (*itr).first << ” : ” << (*itr).second << endl;

    }

  cout<<“the dd map is :”;

    for (itr = dd.begin(); itr != dd.end(); itr++)

    {

        cout << (*itr).first << ” : ” << (*itr).second << endl;

    }

}

  1. count() – it returns the elements that match the specific key.

Student_map.count();

  1. equal_range() – it returns a range of elements matching the specific key.
  2. Upper_range() – Return iterator to the upper bound
  3. lower_range() – Return iterator to the lower bound
  4. key_comp() – it returns function that compares keys.
  5. value_comp() – it returns function that compare keys in objects of type value.

Member Type:

It is used as a parameter or return value in member function. Most of member types are listed below:

  1. key_type
  2. mapped_type
  3. value_type 
  4. key_compare
  5. value_compare
  6. allocator_type
  7. reference
  8. const_reference
  9. pointer
  10. const_pointer
  11. iterator
  12. const_iterator
  13. reverse_iterator
  14. const_reverse_iterator
  15. difference_type
  16. size_type

Destructor in Map:

It destroys the container object. It deallocates memory that allocates by the allocator during the construction of the map.

Advantages of the map:

  1. Map only stores unique keys which eliminates redundancy of data.
  2. Keys are always in sorted order which leads faster traversal in data.
  3. Easy to access the value using the key.

The disadvantage of the map:

  1. In the case of a large number of elements stored in the map, traversing to every element is more time-consuming.

Can we use the map in another map?

Yes we can use nested map, but you have to keep the syntax of the  map .

#include <iostream>

#include <map>

#include <string>

using namespace std;

int main() {

  map<int, map<string, int> > mapinmap;

  mapinmap[12][“mahiraj”]=87;

  cout <<”the marks of roll no. 12  mahiraj is :”<< mapinmap[12][“mahiraj”] << endl;

}

Output:

the marks of roll no. 12  mahiraj is:87

Summary:

In this article, we learned what is a map in C++ in an easy manner. First, we learnt what is the map? Then we go through the STL, Creation of map, Initialization of map, how to access map? What is an iterator? and what iterators can do? Functions used in the map, member type used by the function, advantages and disadvantages of the map and the concept of a nested map.

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

fifteen − 5 =