In C++, std::set::swap()exchanges the contents of two sets. After the call, each 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 <set> to use it.
This is a member of std::set<T>, a sorted container of unique values. A set never keeps a duplicate and always holds its values in sorted order, so it can find, insert, and erase a value in logarithmic time. A set has no operator[] and no at(), because the value is its own key. Every element is const, so you cannot change a value through an iterator.
Syntax
Call it on one set and pass the other. The free function std::swap does the same.
C++
std::set<int> a = {1, 2, 3};
std::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::set<Key, Compare, Alloc>& a, std::set<Key, Compare, Alloc>& b);
Parameters
Parameter
Description
other
The set to exchange contents with. It must have the same type as this 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 set with a two-value set and print both.