C++ std::unordered_map insert_or_assign() Function

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

Definition

In C++17, std::unordered_map::insert_or_assign() does exactly what its name says. If the key is new, it inserts the pair. If the key already exists, it assigns the new value to it.

That is the update that insert() refuses to do. It also works for value types that have no default constructor, which m[key] = value cannot do. Include <unordered_map> and compile with -std=c++17 or newer.

This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. 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 the key and the value. The value is assigned if the key exists.

C++
auto r = m.insert_or_assign("tea", 20);
bool added = r.second;     // true if tea was new
auto it   = r.first;       // iterator to the pair
CallWhat it does
m.insert_or_assign(key, value)Inserts the pair, or assigns value to the existing key. Returns std::pair<iterator, bool>.
m.insert_or_assign(hint, key, value)Same as above, with a position hint. Returns an iterator.

The bool is true when a new pair was inserted and false when an existing value was assigned. Both cases leave the key in the unordered_map with the new value.

Library declarations
C++
template<class M>
std::pair<iterator, bool> insert_or_assign(const Key& key, M&& obj);
template<class M>
std::pair<iterator, bool> insert_or_assign(Key&& key, M&& obj);
template<class M>
iterator insert_or_assign(const_iterator hint, const Key& key, M&& obj);   // C++17

Parameters

ParameterDescription
keyThe key to insert or to update.
objThe value to store. It is assigned to the mapped value if the key exists.
hintOptional iterator near the insertion position. It only affects speed.

Return Value

Return ValueDescription
pair<iterator, bool>first points to the pair. second is true if inserted and false if an existing value was assigned.
iteratorFor the hint form: an iterator to the pair.

C++ Examples

Example 1 — insert_or_assign() Inserts or Updates

Call it twice with the same key and watch the value and the returned flag change.

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

int main() {
    std::unordered_map<std::string, int> price;
    std::cout << std::boolalpha;

    auto r1 = price.insert_or_assign("tea", 10);
    std::cout << "tea new: " << r1.second << ", price " << price["tea"] << '\n';

    auto r2 = price.insert_or_assign("tea", 12);
    std::cout << "tea new: " << r2.second << ", price " << price["tea"] << '\n';
    return 0;
}

How It Works

  1. The first call finds no "tea", so it inserts a new pair. The returned second is true and the price is 10.
  2. The second call finds the existing key and assigns 12 to it. No new pair is made, so second is false.
  3. Both lines read the value with price["tea"]. Since the key exists by then, the bracket operator adds nothing.

Example 2 — insert_or_assign() for Many Updates

Loop over a list of changes. New items are added and old items get their new value.

C++
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>

int main() {
    std::unordered_map<std::string, int> stock = {{"apple", 5}, {"pear", 2}};

    std::vector<std::pair<std::string, int>> changes = {
        {"pear", 8}, {"kiwi", 4}, {"apple", 1}
    };

    for (const auto& c : changes) {
        stock.insert_or_assign(c.first, c.second);
    }

    std::cout << "apple: " << stock.at("apple") << '\n';
    std::cout << "kiwi: " << stock.at("kiwi") << '\n';
    std::cout << "pear: " << stock.at("pear") << '\n';
    return 0;
}

How It Works

  1. stock starts with apple and pear. The vector holds three changes.
  2. pear and apple exist, so their values are replaced by 8 and 1. kiwi is new, so it is added with 4.
  3. Each value is printed with at(), so the output order is stable.

Example 3 — insert_or_assign() and Types Without a Default Constructor

Store a type that has no default constructor, where m[key] = value would not compile.

C++
#include <iostream>
#include <unordered_map>

struct Point {
    int x;
    explicit Point(int value) : x(value) {}
};

int main() {
    std::unordered_map<int, Point> pts;

    // pts[1] = Point(5);  // error: Point has no default constructor
    pts.insert_or_assign(1, Point(5));
    pts.insert_or_assign(1, Point(9));

    std::cout << "x of key 1: " << pts.at(1).x << '\n';
    std::cout << "size: " << pts.size() << '\n';
    return 0;
}

How It Works

  1. Point has only a constructor that needs a number. The bracket operator must create a default Point first, so the commented line would not compile.
  2. insert_or_assign(1, Point(5)) builds the pair directly from the value, so it compiles. The second call finds key 1 and assigns Point(9) to it.
  3. at(1).x shows 9, and the size is 1, because the second call updated instead of adding.

Frequently Asked Questions

It inserts a pair if the key is new, and assigns the new value if the key already exists. Either way, the key ends up with your value.
C++17. Compile with -std=c++17 or newer.
insert() keeps the old value when the key exists. insert_or_assign() replaces the old value with the new one.
Both can update a value, but insert_or_assign() does not need a default constructor for the value type, and it returns a bool that tells you whether the key was new.
true means a new pair was inserted. false means the key existed and its value was assigned.

Next: insert_range()

Keep going through the std::unordered_map functions. Insert every pair from a range in one call (C++23).

insert_range() 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.

10 people found this page helpful