C++ Maps

Welcome to The Coding College! In this tutorial, we’ll explore maps in C++, an essential associative container in the Standard Template Library (STL). Maps are highly versatile when working with key-value pairs.

What Is a Map?

A map in C++ is an associative container that stores key-value pairs, where each key is unique, and values are associated with keys. Keys are automatically sorted in ascending order by default.

Key Characteristics:

  • Unique Keys: No duplicate keys are allowed.
  • Automatic Sorting: Keys are stored in sorted order.
  • Efficient Operations: Optimized for search, insertion, and deletion using a balanced binary tree.

Declaring a Map

To use maps, include the <map> header.

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

int main() {
    map<int, string> myMap; // Declare a map with int keys and string values

    return 0;
}

Common Operations

1. Insert Elements

You can insert key-value pairs using the insert function or the [] operator.

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

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

    // Insert using insert() method
    myMap.insert({1, "One"});
    myMap.insert({2, "Two"});

    // Insert using [] operator
    myMap[3] = "Three";

    for (auto &pair : myMap) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}

Output:

1: One  
2: Two  
3: Three  

2. Access Elements

Use the [] operator to access values by their keys.

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

int main() {
    map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    cout << "Value for key 2: " << myMap[2] << endl;

    return 0;
}

Output:

Value for key 2: Two  

3. Check Size

The size() method returns the number of elements in the map.

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

int main() {
    map<int, string> myMap = {{1, "One"}, {2, "Two"}};

    cout << "Map size: " << myMap.size() << endl;

    return 0;
}

Output:

Map size: 2  

4. Erase Elements

Use the erase() method to remove elements by key.

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

int main() {
    map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    myMap.erase(2); // Remove key 2

    for (auto &pair : myMap) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}

Output:

1: One  
3: Three  

5. Check for Key Existence

Use the find() or count() method to check if a key exists.

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

int main() {
    map<int, string> myMap = {{1, "One"}, {2, "Two"}};

    if (myMap.find(2) != myMap.end()) {
        cout << "Key 2 exists!" << endl;
    }

    cout << "Key 3 exists: " << (myMap.count(3) ? "Yes" : "No") << endl;

    return 0;
}

Output:

Key 2 exists!  
Key 3 exists: No  

6. Iterate Over a Map

You can traverse a map using range-based loops or iterators.

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

int main() {
    map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

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

    return 0;
}

Output:

1: One  
2: Two  
3: Three  

Example: Real-World Application

Frequency Counter

Count the frequency of elements in an array using a map.

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

int main() {
    vector<int> nums = {1, 2, 2, 3, 3, 3};
    map<int, int> freqMap;

    for (int num : nums) {
        freqMap[num]++;
    }

    for (auto &pair : freqMap) {
        cout << "Element " << pair.first << " appears " << pair.second << " times." << endl;
    }

    return 0;
}

Output:

Element 1 appears 1 times.  
Element 2 appears 2 times.  
Element 3 appears 3 times.  

Types of Maps

1. Map

Stores elements in ascending order of keys.

map<int, string> myMap;

2. Multimap

Allows multiple values for the same key.

multimap<int, string> myMultiMap;

3. Unordered Map

Stores elements without any specific order and uses hashing for faster lookups.

unordered_map<int, string> myUnorderedMap;

Summary

  • Advantages: Automatic sorting, efficient key-value storage, quick lookups.
  • Key Methods: insert, erase, find, count, size.
  • Applications: Frequency counting, storing configurations, implementing dictionaries.

Learn More at The Coding College

For more tutorials on C++ and advanced data structures, visit The Coding College.

Leave a Comment