0
0
CppHow-ToBeginner · 3 min read

How to Insert into Map in C++: Syntax and Examples

To insert into a std::map in C++, use the insert() method with a std::pair or use the subscript operator [] to add or update key-value pairs. For example, myMap.insert({key, value}) or myMap[key] = value.
📐

Syntax

There are two common ways to insert elements into a std::map:

  • Using insert(): Inserts a key-value pair if the key does not exist.
  • Using the subscript operator []: Adds a new key with a value or updates the value if the key exists.

Example syntax:

myMap.insert(std::make_pair(key, value));
myMap[key] = value;
cpp
std::map<KeyType, ValueType> myMap;
myMap.insert(std::make_pair(key, value));
myMap[key] = value;
💻

Example

This example shows how to insert elements into a std::map using both insert() and the subscript operator. It prints the map contents after insertion.

cpp
#include <iostream>
#include <map>

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

    // Insert using insert() with std::pair
    ages.insert(std::make_pair("Alice", 30));

    // Insert using subscript operator
    ages["Bob"] = 25;

    // Update value using subscript operator
    ages["Alice"] = 31;

    // Print map contents
    for (const auto& pair : ages) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}
Output
Alice: 31 Bob: 25
⚠️

Common Pitfalls

Common mistakes when inserting into a std::map include:

  • Using insert() with a key that already exists does nothing; the old value remains.
  • Assuming insert() updates existing keys (it does not).
  • Forgetting that the subscript operator [] creates a default value if the key is missing.

Example of wrong and right usage:

cpp
#include <iostream>
#include <map>

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

    // Wrong: insert does not update existing key
    myMap.insert({1, "One"});
    myMap.insert({1, "Uno"}); // ignored, key 1 already exists

    std::cout << "After insert attempts: " << myMap[1] << std::endl; // prints "One"

    // Right: use subscript operator to update
    myMap[1] = "Uno";
    std::cout << "After update: " << myMap[1] << std::endl; // prints "Uno"

    return 0;
}
Output
After insert attempts: One After update: Uno
📊

Quick Reference

MethodDescriptionBehavior on Existing Key
insert()Adds key-value pair if key not presentDoes nothing if key exists
operator[]Adds or updates key-value pairUpdates value if key exists

Key Takeaways

Use insert() to add new key-value pairs without overwriting existing keys.
Use the subscript operator [] to add or update values for a key.
insert() does not update values if the key already exists.
operator[] creates a default value if the key is missing before assignment.
Always check if insert succeeded if you need to know whether insertion happened.