Home C++ C++ Standard Template Library (STL) map tutorial

C++ Standard Template Library (STL) map tutorial

The map container in the C++ Standard Template Library (STL) is an associative container that stores key-value pairs, where each key is unique.

The elements in a map are automatically sorted by keys, which makes it efficient for searching, inserting, and deleting elements based on the key.

Key Features of map

  1. Key-Value Pairs: Each element is stored as a pair of a unique key and a value.
  2. Ordered: Elements are automatically sorted by keys.
  3. Unique Keys: Each key can appear only once in the map.
  4. Efficient Operations: Operations like insertion, deletion, and lookup are efficient.

Basic Syntax

#include <map>
using namespace std;

map<KeyType, ValueType> mp;

Let’s go through various examples to understand how to work with map.

1. Initializing and Inserting Elements

You can initialize a map and insert elements using the insert function or the subscript operator [].

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

int main() {
    // Initialize an empty map
    map<string, int> age;

    // Insert elements using the subscript operator
    age["Alice"] = 25;
    age["Bob"] = 30;

    // Insert elements using insert() with pairs
    age.insert(make_pair("Charlie", 28));

    // Display elements
    cout << "Elements in the map:" << endl;
    for (const auto &pair : age) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}

Output:

Elements in the map:
Alice: 25
Bob: 30
Charlie: 28

2. Accessing Elements

Elements in a map can be accessed using the subscript operator [] or at function.

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    // Access using subscript operator
    cout << "Alice's age: " << age["Alice"] << endl;

    // Access using at() function
    cout << "Bob's age: " << age.at("Bob") << endl;

    return 0;
}

Output:

Alice's age: 25
Bob's age: 30

3. Modifying Elements

You can modify the value of a key by assigning a new value using the subscript operator [].

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    // Modify Bob's age
    age["Bob"] = 35;

    cout << "Updated age of Bob: " << age["Bob"] << endl;

    return 0;
}

Output:

Updated age of Bob: 35

4. Checking if a Key Exists

You can use the find function or count function to check if a specific key exists in the map.

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}};

    // Using find()
    if (age.find("Charlie") != age.end()) {
        cout << "Charlie is in the map." << endl;
    } else {
        cout << "Charlie is not in the map." << endl;
    }

    // Using count()
    if (age.count("Alice") > 0) {
        cout << "Alice is in the map." << endl;
    } else {
        cout << "Alice is not in the map." << endl;
    }

    return 0;
}

Output:

Charlie is not in the map.
Alice is in the map.

5. Removing Elements

The erase function removes elements by key or by iterator position.

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    // Remove an element by key
    age.erase("Bob");

    // Display remaining elements
    cout << "Elements after removing Bob:" << endl;
    for (const auto &pair : age) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}

Output:

Elements after removing Bob:
Alice: 25
Charlie: 28

6. Iterating Over Elements

You can use a for loop or iterators to iterate over elements in a map.

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    cout << "Ages:" << endl;
    for (auto it = age.begin(); it != age.end(); ++it) {
        cout << it->first << ": " << it->second << endl;
    }

    return 0;
}

Output:

Ages:
Alice: 25
Bob: 30
Charlie: 28

7. Finding an Element

The find function returns an iterator to the element if it exists; otherwise, it returns map::end.

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    auto it = age.find("Charlie");
    if (it != age.end()) {
        cout << "Found Charlie's age: " << it->second << endl;
    } else {
        cout << "Charlie is not in the map." << endl;
    }

    return 0;
}

Output:

Found Charlie's age: 28

8. Using map with Custom Comparator

You can define a custom comparator to change the order of keys in the map.

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

struct DescendingOrder {
    bool operator()(const string &a, const string &b) const {
        return a > b;
    }
};

int main() {
    map<string, int, DescendingOrder> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    cout << "Elements in descending order of keys:" << endl;
    for (const auto &pair : age) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}

Output:

Elements in descending order of keys:
Charlie: 28
Bob: 30
Alice: 25

9. Counting Elements

Although map only stores unique keys, you can use count to check if a specific key exists (it returns 0 or 1).

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}};

    cout << "Count of 'Alice': " << age.count("Alice") << endl;
    cout << "Count of 'Charlie': " << age.count("Charlie") << endl;

    return 0;
}

Output:

Count of 'Alice': 1
Count of 'Charlie': 0

10. Clearing the Map

The clear function removes all elements from the map, making it empty.

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

int main() {
    map<string, int> age = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 28}};

    cout << "Size before clear: " << age.size() << endl;

    // Clear the map
    age.clear();

    cout << "Size after clear: " << age.size() << endl;

    return 0;
}

Output:

Size before clear: 3
Size after clear: 0

Summary Table of map Operations

Operation Code Example Description
Initialize map<string, int> mp = {{“Alice”, 25}}; Creates a map with initial values
Insert element mp[“Bob”] = 30; Inserts or updates an element
Access element mp.at(“Alice”); Accesses the value associated with a key
Modify element mp[“Alice”] = 35; Modifies the value associated with a key
Check if key exists mp.find(“Charlie”) != mp.end(); Checks if a key exists
Remove element mp.erase(“Alice”); Removes an element by key
Iterate for (auto &p : mp) Iterates over elements
Count elements mp.count(“Alice”); Checks if a key exists (returns 0 or 1)
Clear map mp.clear(); Removes all elements
Custom comparator map<string, int, CustomComparator> mp; Creates a map with custom sorting

Complete Example

This example demonstrates initializing a map, inserting, accessing, modifying, removing, and iterating over elements, as well as using count and clear.

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

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

    // Insert elements
    age["Alice"] = 25;
    age["Bob"] = 30;
    age.insert(make_pair("Charlie", 28));

    // Access elements
    cout << "Alice's age: " << age["Alice"] << endl;

    // Modify element
    age["Bob"] = 35;

    // Check if key exists
    if (age.find("Charlie") != age.end()) {
        cout << "Charlie found, age: " << age["Charlie"] << endl;
    }

    // Count elements
    cout << "Count of 'Alice': " << age.count("Alice") << endl;

    // Remove element
    age.erase("Alice");

    // Display all elements
    cout << "Elements in the map:" << endl;
    for (const auto &pair : age) {
        cout << pair.first << ": " << pair.second << endl;
    }

    // Clear the map
    age.clear();
    cout << "Size after clear: " << age.size() << endl;

    return 0;
}

Sample Output:

Alice's age: 25
Charlie found, age: 28
Count of 'Alice': 1
Elements in the map:
Bob: 35
Charlie: 28
Size after clear: 0

Key Takeaways

  • map is an associative container that stores key-value pairs in sorted order by key, supporting efficient search, insert, and delete operations.
  • Use [] and at() for accessing and modifying values.
  • Functions like insert, find, erase, and count make it versatile for handling key-based data.
  • Custom comparators allow control over key sorting, while iterators provide flexibility for traversal and manipulation.

 

You may also like