C++ swap()

Anonymous contributor's avatar
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.

  • 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

Syntax of C++ swap()

set1.swap(set2);

Or using the non-member function:

std::swap(set1, set2);

Parameters:

  • set1, set2: Two std::set containers 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 swap
std::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 8
After 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:

Code
Output
Loading...

All contributors

Contribute to 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