C++ std::map insert() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::map

Definition

In C++, std::map::insert() adds a new pair to a std::map. The pair goes to the right place so that the keys stay sorted.

If the key is already in the map, insert() does nothing and the old value stays. The m[key] = value form is different: it creates the key if needed and always overwrites the value. Include <map> to use it.

This is a member of std::map<Key, T>, a sorted container of key and value pairs. Each key is unique and the pairs are always kept in key order, so a map can find, insert, and erase a key in logarithmic time. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.

Syntax

Pass a pair, a braced pair, an initializer list, or a range of pairs.

C++
auto r = m.insert({"one", 1});        // one pair
m.insert(std::make_pair("two", 2));   // pair made with make_pair
m.insert({{"c", 3}, {"d", 4}});       // initializer list
m.insert(other.begin(), other.end()); // a range of pairs
CallWhat it does
m.insert(pair)Adds the pair if its key is new. Returns std::pair<iterator, bool>.
m.insert(hint, pair)Same, but uses hint as a starting position to be faster. Returns an iterator.
m.insert(first, last)Inserts every pair from the range. Pairs with keys that already exist are skipped.
m.insert({p1, p2, ...})Inserts all pairs in the initializer list, skipping duplicate keys.
m.insert(std::move(node))Inserts a node handle from extract() (C++17).

Since C++17 you also have insert_or_assign() to update existing values and try_emplace() to avoid wasted work. emplace() builds the pair in place.

Library declarations
C++
std::pair<iterator, bool> insert(const value_type& value);
std::pair<iterator, bool> insert(value_type&& value);
iterator insert(const_iterator hint, const value_type& value);
template<class InputIt> void insert(InputIt first, InputIt last);
void insert(std::initializer_list<value_type> ilist);
insert_return_type insert(node_type&& nh);   // C++17

Parameters

ParameterDescription
valueThe pair to add, of type std::pair<const Key, T>. A braced pair such as {"one", 1} works.
hintAn iterator near where the pair will go. It only helps speed; it does not change the result.
first, lastA range of pairs to insert.
ilistA braced list of pairs.
nhA node handle returned by extract().

Return Value

Return ValueDescription
pair<iterator, bool>first points to the pair with that key. second is true if a new pair was added, and false if the key already existed.
iteratorFor the hint form: an iterator to the pair with that key, new or old.
voidFor the range and initializer list forms.

C++ Examples

Example 1 — insert() Reports If It Added the Pair

Insert the same key twice and read the bool that insert() returns.

C++
#include <iostream>
#include <map>
#include <string>

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

    auto r1 = m.insert({"one", 1});
    auto r2 = m.insert({"one", 100});

    std::cout << "first insert added: " << r1.second << '\n';
    std::cout << "second insert added: " << r2.second << '\n';
    std::cout << "value is still: " << r2.first->second << '\n';
    return 0;
}

How It Works

  1. insert({"one", 1}) finds no key "one", so it adds the pair. The returned second is true.
  2. The second insert uses the same key. The map keeps keys unique, so it adds nothing and second is false.
  3. r2.first is an iterator to the existing pair, and its value is still 1. The 100 was thrown away.

Example 2 — insert() with a List and a Range

Add pairs with an initializer list and then with a range from another map.

C++
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> m = {{"b", 2}};
    std::map<std::string, int> other = {{"d", 4}, {"a", 50}};

    m.insert({{"c", 3}, {"a", 1}, {"b", 99}});
    m.insert(other.begin(), other.end());

    for (const auto& kv : m) {
        std::cout << kv.first << "=" << kv.second << ' ';
    }
    std::cout << "(size " << m.size() << ")\n";
    return 0;
}

How It Works

  1. The list form adds c and a. The pair {"b", 99} is skipped because "b" already exists, so b stays 2.
  2. The range form copies pairs from other. d is new and added. {"a", 50} is skipped because a is already 1.
  3. The map keeps keys sorted, so the loop prints a, b, c, d even though they were inserted in a mixed order.

Example 3 — insert() Compared with operator[]

See that insert() keeps old values, that [] overwrites them, and that reading with [] can add a key.

C++
#include <iostream>
#include <map>
#include <string>

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

    m.insert({"x", 1});
    m.insert({"x", 2});      // ignored
    m["y"] = 1;
    m["y"] = 2;              // overwrites

    int q = m["q"];          // only reading, but q is added with 0
    std::cout << "q = " << q << ", size = " << m.size() << '\n';

    for (const auto& kv : m) {
        std::cout << kv.first << "=" << kv.second << ' ';
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. insert({"x", 2}) is ignored because "x" exists, so x keeps the value 1.
  2. m["y"] = 2 overwrites the earlier 1, because the bracket operator assigns every time.
  3. m["q"] does not find "q", so it inserts it with the default 0 even though you only read it. That is why the size is 3 and q=0 appears.

Frequently Asked Questions

The single-pair form returns std::pair<iterator, bool>. The iterator points at the pair with that key, and the bool is true only if a new pair was added.
Nothing. The map is not changed and the old value stays. The returned bool is false.
insert() adds only new keys and keeps old values. m[key] = value adds the key if needed and always sets the value. Also, m[key] on a missing key inserts a default value even when you only read it.
Use m[key] = value, m.at(key) = value, or insert_or_assign() in C++17. insert() will not update it.
Yes. The pair is placed so the keys stay in order. You do not sort a std::map yourself.

Next: insert_or_assign()

Keep going through the std::map functions. Insert a new key, or update the value if the key exists (C++17).

insert_or_assign() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful