0
0
CppHow-ToBeginner · 3 min read

How to Create Map in C++: Syntax and Examples

In C++, you create a map using the std::map container from the <map> header. It stores key-value pairs with unique keys and allows fast lookup by key.
📐

Syntax

The basic syntax to create a map is:

  • std::map<KeyType, ValueType> mapName; creates an empty map.
  • KeyType is the type of the keys (e.g., int, std::string).
  • ValueType is the type of the values stored for each key.

You can insert elements using mapName[key] = value; or mapName.insert({key, value});.

cpp
std::map<KeyType, ValueType> mapName;
💻

Example

This example shows how to create a map of strings to integers, add elements, and print them.

cpp
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> ageMap;

    // Add elements
    ageMap["Alice"] = 30;
    ageMap["Bob"] = 25;
    ageMap.insert({"Charlie", 35});

    // Print all elements
    for (const auto& pair : ageMap) {
        std::cout << pair.first << " is " << pair.second << " years old.\n";
    }

    return 0;
}
Output
Alice is 30 years old. Bob is 25 years old. Charlie is 35 years old.
⚠️

Common Pitfalls

Common mistakes when using maps include:

  • Using map[key] to check if a key exists, which inserts a default value if the key is missing.
  • Not including the <map> header.
  • Assuming maps keep insertion order (they sort keys automatically).

Use map.find(key) to check if a key exists without inserting.

cpp
#include <iostream>
#include <map>

int main() {
    std::map<int, int> m;

    // Wrong: This inserts key 1 with default value 0 if not found
    if (m[1] != 0) {
        std::cout << "Key 1 exists\n";
    } else {
        std::cout << "Key 1 does not exist\n";
    }

    // Right: Use find() to check existence
    if (m.find(1) != m.end()) {
        std::cout << "Key 1 exists\n";
    } else {
        std::cout << "Key 1 does not exist\n";
    }

    return 0;
}
Output
Key 1 does not exist Key 1 does not exist
📊

Quick Reference

Summary tips for using std::map:

  • Include <map> and <string> if needed.
  • Maps store unique keys sorted by default.
  • Use map[key] = value; to insert or update.
  • Use map.find(key) to check if a key exists without inserting.
  • Iterate with range-based for loops for easy access.

Key Takeaways

Use std::map<KeyType, ValueType> to create a map with unique sorted keys.
Insert or update elements with map[key] = value;.
Check key existence with map.find(key) to avoid unwanted insertions.
Maps automatically sort keys; they do not preserve insertion order.
Always include the <map> header to use maps.