What is the C++ STL map?

Maps are a part of the C++ STL. Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values.

In C++, maps store the key values in ascending order by default.

A visual representation of a C++ map.
A visual representation of a C++ map.

Syntax

The basic syntax to initialize a C++ STL map is as follows:

A visual representation of a C++ map.
A visual representation of a C++ map.

Hence, to declare a map with string values as keys, ​and integers as their corresponding values, we’ll use the following code:

map<string, int> sample_map;

Built-in functions

STL Maps come with some basic built-in functions. Some of them are explained below:

  • begin(): Returns an iterator to the first element in the map.

  • size(): Returns the number of elements in the map.

  • empty(): Returns a boolean value indicating whether the map is empty.

  • insert( pair(key, value)): Adds a new key-value pair to the map. An alternate way to insert values in the map is:

map_name[key] = value;
  • find(val): Gives the iterator to the element val, if it is found otherwise it returns m.end()

  • erase(iterator position): Removes the element at the position pointed by the iterator.

  • erase(const g): Removes the key value g from the map.

  • clear(): Removes all the elements from the map.

Example

The following sample program uses some of the functions described above. It first inserts different values into the map and then iterates for a value corresponding to a particular key.

#include <string.h>
#include <iostream>
#include <map>
#include <utility>
using namespace std;
int main()
{
// Initializing a map with integer keys
// and corresponding string values
map<int, string> Employees;
//Inserting values in map using insert function
Employees.insert ( std::pair<int, string>(101,"Jon") );
Employees.insert ( std::pair<int, string>(103,"Daenerys") );
Employees.insert ( std::pair<int, string>(104,"Arya") );
// Inserting values using Array index notation
Employees[105] = "Sansa";
Employees[102] = "Tyrion";
cout << "Size of the map is " << Employees.size() << endl << endl;
// Printing values in the map
cout << endl << "Default Order of value in map:" << endl;
for( map<int,string>::iterator iter=Employees.begin(); iter!=Employees.end(); ++iter)
{
cout << (*iter).first << ": " << (*iter).second << endl;
}
// Finding the value corresponding to the key '102'
std::map<int, string>::iterator it = Employees.find(102);
if (it != Employees.end()){
std::cout <<endl<< "Value of key = 102 => " << Employees.find(102)->second << '\n';
}
}
Copyright ©2024 Educative, Inc. All rights reserved