static std::map in C++

In this tutorial, we will learn how to use std maps and how to Initialize a static std::map in C++. So map or maps are associative containers that help us stores information or elements formatted by a combination of key values and mapped values, unlike vectors which maintain their values on the basis of the index. The maps maintain their values on basis of keys so they are associative containers. It contains key-value pairs that have unique keys. Just like associative arrays and associative sets the maps work on the basis of keys we provide the information with the help of the key. They help us store elements that can be represented in a mapped fashion. These maps are really helpful in assigning values in the form of keys.

 

Implementing static std::map in C++

#include <iostream>
#include<map>
using namespace std;
  • We are importing maps from our library because Maps help us store elements that can be represented in a mapped fashion basically these are associative containers. Each element contains a key value and a mapped value.
int main()
{
  std::map<int , std::string> students_map;
  students_map[1]="Anmol";
  students_map[2]="Ayush";
  students_map[3]="Tanmay";
  students_map[4]="Riddhu";
  students_map[5]="Soumya";
 	
  std::cout<<students_map[2]<<std::endl;
 	
 	return 0;
 	
}
  • Int is the data type of the key-value.
  • std::string is the data type of mapped value.

 

Output

Ayush

 

You cannot have two similar keys because you cannot duplicate keys as they are associative and if you have duplicate keys it gives you the last assigned value to the key as an output. Eg:-

#include <iostream>
#include<map>
using namespace std;
int main()
{
  std::map<int , std::string> students_map;
  students_map[1]="Anmol";
  students_map[2]="Ayush";
  students_map[3]="Tanmay";
  students_map[4]="Riddhu";
  students_map[4]="Riddhu duplicate";
  students_map[5]="Soumya";
 	
  std::cout<<students_map[4]<<std::endl;
 	
 	return 0;
 	
}

 

Output

Riddhu duplicate

We can see that since the last assigned value to key 4 is “Riddhu duplicate” it gives it as an output.

Also read: Naive Algorithm for Pattern Searching in C++

Leave a Reply

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