C++ std::unordered_map swap() Function

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

Definition

In C++, std::unordered_map::swap() exchanges everything between two unordered_maps of the same type. After the call, each map holds what the other one held before.

It is very fast, because only the internal links are swapped. No pair is copied, moved, or destroyed. Include <unordered_map> to use it.

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

Call swap on one map and pass the other.

C++
a.swap(b);            // member function
std::swap(a, b);      // non-member function (same result)
CallWhat it does
a.swap(b)Exchanges the contents of a and b. Both unordered_maps must have the same type.
std::swap(a, b)The non-member version. It simply calls a.swap(b).

Swapping is a common way to publish a freshly built map: build a new map on the side, then swap it with the old one in one quick step.

Library declarations
C++
void swap(map& other) noexcept(/* see below */);
// non-member:
template<class Key, class T, class Cmp, class Alloc>
void swap(map<Key, T, Cmp, Alloc>& lhs, map<Key, T, Cmp, Alloc>& rhs);

Parameters

ParameterDescription
otherThe unordered_map to exchange contents with. It must have the same key, value, comparator, and allocator types.

Return Value

Return ValueDescription
voidNothing is returned. The two unordered_maps now hold each other's old content.

C++ Examples

Example 1 — swap() Exchanges Two Unordered maps

Swap two small unordered_maps and print both.

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

int main() {
    std::unordered_map<int, std::string> a = {{1, "one"}};
    std::unordered_map<int, std::string> b = {{2, "two"}, {3, "three"}};

    a.swap(b);

    std::cout << "a has " << a.size() << " pairs, first key " << a.begin()->first << '\n';
    std::cout << "b has " << b.size() << " pair, first key " << b.begin()->first << '\n';
    return 0;
}

How It Works

  1. Before the call, a holds key 1 and b holds keys 2 and 3.
  2. a.swap(b) exchanges the whole contents. It only swaps internal links, so it is fast no matter how many pairs there are.
  3. Now a holds the two pairs with first key 2, and b holds the single pair with key 1.

Example 2 — swap() and Iterators

An iterator taken before the swap now points into the other map.

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

int main() {
    std::unordered_map<int, std::string> a = {{1, "one"}};
    std::unordered_map<int, std::string> b = {{2, "two"}, {3, "three"}};

    auto it = a.begin();          // points at key 1 inside a
    a.swap(b);                    // that pair now lives in b

    std::cout << std::boolalpha;
    std::cout << "value: " << it->second << '\n';
    std::cout << "it is b.begin(): " << (it == b.begin()) << '\n';
    return 0;
}

How It Works

  1. it is taken from a before the swap. It points to the pair 1 -> "one".
  2. The swap moves ownership of the whole tree, not the pairs. The pair is not copied, so it stays valid and still reads one.
  3. That pair now belongs to b and is its only element, so it == b.begin() is true.

Example 3 — swap() to Replace a Map

Build a new map on the side and swap it in. The old data ends up in the temporary map.

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

int main() {
    std::unordered_map<std::string, int> current = {{"old", 1}};
    std::unordered_map<std::string, int> fresh;

    fresh["new"] = 2;
    fresh["newer"] = 3;

    current.swap(fresh);

    std::cout << "current has " << current.size() << " keys, new exists: "
              << std::boolalpha << current.contains("new") << '\n';
    std::cout << "fresh holds the old data, size " << fresh.size() << '\n';
    return 0;
}

How It Works

  1. fresh is filled with the new data while current is still untouched. This can take as long as needed.
  2. current.swap(fresh) replaces the content in one step. Readers of current never see a half-built map. (This example uses contains(), which needs C++20.)
  3. After the swap, current holds two keys, and fresh holds the old single pair. When fresh goes out of scope, the old data is freed.

Frequently Asked Questions

It exchanges the entire contents of two unordered_maps of the same type, in constant time.
No. It only swaps internal pointers, so it does not copy, move, or destroy any pair.
No. They stay valid but now refer to elements in the other map. The end() iterators are the exception.
Yes. The non-member std::swap for unordered_maps just calls the member function.
No. Both unordered_maps need the same key, value, comparator, and allocator types.

Next: try_emplace()

Keep going through the std::unordered_map functions. Add a pair only if the key is new, without touching your arguments (C++17).

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

12 people found this page helpful