C++ Maps Part I

A.What are maps, first?

In the C++ STL, a map is a key-value pair-storing associative container. To be more specific, a map keeps track of a key of one data type and its corresponding values of another. All of the values and all of the keys in a map have the same data type. These key-value pairs are always arranged in ascending order by the key components in a map.

B. Incorporating maps into our programmes

The header file map> must be present in our code in order to use maps. And a map’s definition syntax is

map<data_type_of_key, data_type_of_value> map_name;

Any data type may be used in place of data type, and they may differ for both key and value.

A map’s components can be accessed and used using specific procedures. Some of them are talked about. Visit this website, std::map, to view all the methods and member functions in detail.

c. Initializing a map,

Similar to how we initialised a vector or a list, we may initialise a map in the same manner. Just that when we initialise a map, it would be pairs of elements rather to just single elements. When a map is defined, all the key-value pairs that will eventually be stored in the map may be added as initial values.

map<string, int> m = {{“Harry”, 2}, {“Rohan”, 4}};

D. Adding components to a map

Different methods can be used to add components to a map. Any element can be added to a map in logarithmic time, which is quicker than in vectors or arrays but slower than in lists.

The index operators [] could be used to insert data into a map. The operator contains the key, and the value is then assigned to it. The map is then updated with this key-value pair.

#include <iostream>
#include <map>
using namespace std;
 
void display(map<string, int> m)
{
    cout << "The elements are: " << endl;
    for (auto it : m)
    {
        cout << it.first << " -> " << it.second << endl;
    }
    cout << endl;
}
 
int main()
{
    map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
    display(m);
    m["Coder"] = 3;
    display(m);
}

Output:

Harry -> 2
Rohan -> 4

The elements are:
Coder -> 3
Harry -> 2
Rohan -> 4

We can enter as many key-value pairs as we like by using the insert() method, which is another way to insert an element. The insert method’s syntax is as follows:

map_name.insert({key-value pair});

Here’s an illustration of how to utilise the insert() method:

map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m.insert({{"Coder", 3}, {"Rahul", 5}});
display(m);

Output:

The elements are: 
Harry -> 2
Rohan -> 4

The elements are:
Coder -> 3
Harry -> 2
Rahul -> 5
Rohan -> 4
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in