In C++, std::unordered_set::swap()exchanges the contents of two sets. After the call, each unordered_set holds what the other one had.
It works in constant time, because only internal pointers are swapped. No value is copied or moved, and no value is destroyed. Both sets must have the same type. Include <unordered_set> to use it.
This is a member of std::unordered_set<T>, a hash table of unique values. Find, insert, and erase are usually average constant time. Unlike std::set, values are not sorted and iteration order is unspecified. Elements are const, so you cannot change a stored value through an iterator. There is no operator[] and no at(). Prefer find() or contains() to look up a value, and call reserve() before many inserts.
Syntax
Call it on one set and pass the other. The free function std::swap does the same.
C++
std::unordered_set<int> a = {1, 2, 3};
std::unordered_set<int> b = {7, 8};
a.swap(b); // a: 7 8 b: 1 2 3
std::swap(a, b); // swap back
Call
What it does
a.swap(b)
Exchanges the contents of a and b. Returns nothing.
std::swap(a, b)
The non-member version. It calls a.swap(b) for you.
Both sets must be the same type, including the comparison. After the swap, an iterator that pointed into a still points to the same value, but that value now lives in b. The end() iterators are the exception, because they still belong to their original sets.
Library declarations
C++
void swap(set& other) noexcept(/* see C++ standard */);
template<class Key, class Compare, class Alloc>
void swap(std::unordered_set<Key, Compare, Alloc>& a, std::unordered_set<Key, Compare, Alloc>& b);
Parameters
Parameter
Description
other
The unordered_set to exchange contents with. It must have the same type as this unordered_set.
Return Value
Return Value
Description
void
Nothing is returned. Both sets are changed.
C++ Examples
Example 1 — swap() Exchanges Contents
Swap a three-value unordered_set with a two-value set and print both.