C++ swap()
Anonymous contributor
Published Oct 30, 2025
Contribute to Docs
The swap() method in C++ exchanges the contents of two std::set containers of identical type (same key type, comparator type, and allocator type). This operation is typically faster than copying or moving elements individually, as it swaps internal pointers and metadata without modifying or relocating the actual elements.
Syntax of C++ swap()
set1.swap(set2);
Or using the non-member function:
std::swap(set1, set2);
Parameters:
set1,set2: Twostd::setcontainers of the same type (including the same key type, comparator, and allocator).
Return value:
- The
swap()method does not return anything. It simply swaps the contents.
Example
In this example, std::swap() is used to exchange the contents of two integer sets named odds and evens:
#include <iostream>#include <set>#include <algorithm>int main() {std::set<int> odds {1, 3, 5, 7};std::set<int> evens {2, 4, 6, 8};std::cout << "Before swap → odds: ";for (int n : odds) std::cout << n << ' ';std::cout << "| evens: ";for (int n : evens) std::cout << n << ' ';std::cout << '\n';std::swap(odds, evens); // non‑member swapstd::cout << "After swap → odds: ";for (int n : odds) std::cout << n << ' ';std::cout << "| evens: ";for (int n : evens) std::cout << n << ' ';std::cout << '\n';}
The output of this code is:
Before swap → odds: 1 3 5 7 | evens: 2 4 6 8After swap → odds: 2 4 6 8 | evens: 1 3 5 7
Codebyte Example
In this example, the member function swap() is used to swap the contents of two string sets, a and b:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours