C++ map

A map in C++ is a container that stores data in key-value pairs. Each key is unique, and it is associated with a value. The keys are automatically sorted, and you can use them to look up the corresponding values quickly.

Key: A unique identifier (e.g., an integer, string).

Value: The data associated with that key (e.g., a name, a number).

Example:


#include <iostream>
#include <map>
using namespace std;

int main() {
    map<int, string> employeeMap;

    // Insert key-value pairs
    employeeMap[1] = "John";
    employeeMap[2] = "Tom";
    employeeMap[3] = "Mark";

    // Iterate over the map and print key-value pairs
    for (const auto& emp : employeeMap) {
        cout << emp.first << " => " << emp.second << endl;
    }

    return 0;
}

Output:

1 => John
2 => Tom
3 => Mark

Insert element in Map

You can insert a key-value pair using the bracket [] operator or insert() method.


employeeMap[4] = "Rom";   // Using []
employeeMap.insert({5, "Porter"});  // Using insert()

Accessing Values from elements

Use the key to access the associated value.


string value = employeeMap[1];  // Access value associated with key 1

Find Operation

You can search for a key using find(), which returns an iterator to the element.


auto findEmp = employeeMap.find(2);
    if (findEmp != employeeMap.end()) {
        cout << "Found: " << findEmp->second << std::endl;
    }

Remove element from elements

You can remove elements by key using erase().


employeeMap.erase(2);  // Removes the element with key 2

Get the number of elements.

You can get the number of elements in the map using size().


cout << "Size: " << employeeMap.size() << std::endl;