map<data_type_of_key, data_type_of_value> map_name;
Table of Contents
Table of Contents
Introduction
C++ is an object-oriented programming language that is widely used in the development of software applications. One of the most commonly used data structures in C++ is the map. A map is an associative container that stores elements in a key-value pair. In this article, we will discuss the usage and implementation of map in C++ programiz.What is a Map?
A map is a container that stores elements in a key-value pair. The key is used to access the element value. In simple words, a map acts as a dictionary where keys are the words and values are the meanings.How to Declare a Map?
To declare a map in C++, we use the map header file. The syntax for declaring a map is as follows: map
map
Adding Elements to a Map
We can add elements to a map using the insert() function. The insert() function takes a key-value pair as its argument, and it inserts the element into the map. The syntax for inserting an element into a map is as follows:map_name.insert(make_pair(key, value));
For example, to add an element with key 1 and value "one" to the map, we can use the following code:my_map.insert(make_pair(1, "one"));
Accessing Elements from a Map
We can access elements from a map using the [] operator or the find() function. The [] operator returns the value associated with the key, and the find() function returns an iterator to the element. For example, to access the value associated with key 1, we can use the following code:string value = my_map[1];
Removing Elements from a Map
We can remove elements from a map using the erase() function. The erase() function takes a key as its argument, and it removes the element from the map. For example, to remove the element with key 1 from the map, we can use the following code:my_map.erase(1);
Size of a Map
We can get the size of a map using the size() function. The size() function returns the number of elements in the map. For example, to get the size of the map, we can use the following code:int size = my_map.size();
Map Iterators
We can use iterators to traverse a map. The begin() function returns an iterator to the first element in the map, and the end() function returns an iterator to the last element in the map. For example, to traverse the map and print all the elements, we can use the following code:for(auto it = my_map.begin(); it != my_map.end(); it++) {
cout << it->first << " - " << it->second << endl;
}