Maps
Introduction to Maps in C++
Maps in C++ are part of the Standard Template Library (STL). They are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.
Maps are typically implemented as binary search trees.
Declaration of Maps
A map in C++ is declared as follows:
map <key_type, data_type> map_name;
For example, to create a map named student
that maps an integer to a string, you would write:
map <int, string> student;
Accessing Values in a Map
The mapped values in a map can be accessed directly using their corresponding key values. For instance, to access the value of student
with key 1
, you would write:
cout << student[1];
Inserting Values into a Map
There are two ways you can insert values into a map.
- By using the
insert
function.
student.insert(pair <int, string> (1, "John"));
This statement inserts a key-value pair into the map student
with key 1
and value John
.
- By using the
[]
operator.
student[2] = "Tom";
This statement inserts a key-value pair into the map student
with key 2
and value Tom
.
Size of a Map
The size()
function can be used to find the number of elements (key-value pairs) in a map.
cout << student.size();
Checking If a Map Is Empty
The empty()
function returns true
if the map is empty and false
otherwise.
if(student.empty())
cout << "The map is empty";
else
cout << "The map is not empty";
Deleting Elements from a Map
The erase()
function can be used to remove elements from a map.
student.erase(1);
This statement removes the element with key 1
from the map student
.
Clearing a Map
The clear()
function removes all elements from the map.
student.clear();
Iterating Over a Map
You can use an iterator to access the key-value pairs in a map. Here's how you can do it:
map <int, string> :: iterator it;
for(it = student.begin(); it != student.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
In this code, it->first
represents the key and it->second
represents the value.
Conclusion
Maps in C++ STL are a powerful and flexible tool that allow you to store and manipulate data in a key-value format. They are particularly useful when you need to quickly access data associated with specific keys. Keep practicing with maps to become more familiar with their functionality and uses.