Associative Containers std::map in C++

Anatomy of std::map

Maps are associative containers that store paired data. These paired data are called key-value pairs, where the key is unique but the value is not.

The elements in a map are internally sorted by their keys.

In order to use maps in C++, we must need to include map header file.

#include <map>

Basics of std::map

Associative Container:

  • std::map is an associative container that maintains a collection of key-value pairs, where each key is unique. This ensures efficient search and retrieval operations.

Ordered Structure:

  • One of the defining features of std::map is that if maintains its elements in a sorted order based on the keys. This is achieved through a balanced binary search tree, often a Red-Black Tree.

Key Characteristics:

  • Unique Keys: Each key in a std::map must be unique. Attempting to insert a duplicate key will overwrite the existing value associated with that key.

Creating a Map

We can declare a map using the following syntax:

std::map<key_type, value_type> map_name = {{key1, value1}, {key2, value2}, ...};

Here, key_type - the data type of the keys to be stored in the map.

value_type - the data type of the values to be stored in the map.

map_name - a unique name given to the map.

key1, key, … - keys to be stored in the map.

value1, value2, … - values to be stored in the map.

For example:

std::map<int, string> student = {{1, "MaK"}, {2, "Jack"}, {3, "Rack"}};

we can also initialize map elements without using the assignment operator. For example:

std::map<int, string> student {{1, "MaK"}, {2, "Jack"}, {3, "Rack"}};

Functions

1. Initialization and Assignment:

Default Constructor:

  • Creates an empty map.
std::map<int, std::string> myMap; // Empty map

Range Constructors:

  • Constructs a map using elements from a range of another map.
std::map<int, std::string> sourceMap = {{1, "One"}, {2, "Two"}};
std::map<int, std::string> myMap(sourceMap.begin(), sourceMap.end());

Initializer Lists:

  • Initializes a map using an initializer list.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};

Copy Constructor:

  • Creates  a map by copying another map.
std::map<int, std::string> originalMap = {{1, "One"}, {2, "Two"}};
std::map<int, std::string> myMap(originalMap);

2. Element Access:

Bracket Operator:

  • Accesses or inserts an element.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
std::string value = myMap[1]; // Access value associated with key 1

#include<iostream>
#include<map>

int main(){
    std::map<std::string, std::string> myMap = {{"1", "One"}, {"2", "Two"}};
    std::string value = myMap["1"]; // Access value associated with key 1
    std::cout << value;
    return 0;
}

// Output
One

At Function:

  • Accesses an element with bounds checking.

#include<iostream>
#include<map>

int main(){
    std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
    std::string value = myMap.at(1); // Access value associated with key 1

    std::cout << value;
    return 0;
}

// Output
One

3. Insertion and Deletion

Insert():

  • Inserts an element into the map.
std::map<int, std::string> myMap;
myMap.insert({1, "One"});

Insert with Hint:

  • Inserts an element with a hint on where to start the search.
std::map<int, std::string> myMap;
auto hint = myMap.begin();
myMap.insert(hint, {1, "One"});

Insert Range:

  • Inserts elements from a range.
std::map<int, std::string> myMap;
std::map<int, std::string> sourceMap = {{1, "One"}, {2, "Two"}};
myMap.insert(sourceMap.begin(), sourceMap.end());

Erase():

  • Removes an element from the map.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
myMap.erase(1); // Remove the element with key 1

Erase by Iterator:

  • Removes an element using an iterator.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
auto it = myMap.find(2);
if (it != myMap.end()) {
    myMap.erase(it); // Remove the element found
}

4. Search and Count:

Find Function:

  • Searches for an element.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
auto it = myMap.find(2);
if (it != myMap.end()) {
    // Element found
}

Count Function:

  • Counts the occurrences of a specific key.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
size_t count = myMap.count(2);

5. Size and Capacity:

Size Function:

  • Returns the number of elements in the map.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
size_t size = myMap.size();

Empty Function:

  • Checks if the map is empty.
std::map<int, std::string> myMap;
bool isEmpty = myMap.empty();

6. Iterators:

Begin and End Functions:

  • Returns iterators pointing to the beginning and end of the map.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
auto beginIt = myMap.begin();
auto endIt = myMap.end();

Iterator Loop:

  • Iterates through the elements of the map.
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
    // Access it->first (key) and it->second (value)
}

7. Clear Function:

Clear Function:

  • Removes all elements from the map.
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
myMap.clear();

8. Comparison Operators:

Equality and Inequality Operators:

  • Compares two maps for equality or inequality.
std::map<int, std::string> map1 = {{1, "One"}, {2, "Two"}};
std::map<int, std::string> map2 = {{1, "One"}, {2, "Two"}};
if (map1 == map2) {
    // Maps are equal
}