C++ .swap()

emeraldLife's avatar
Published Oct 29, 2025
Contribute to Docs

In C++, the .swap() function swaps the values of two queues. The queues must have the same data type, although size can differ.

  • 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

The .swap() method can be used with the following syntax:

queue1.swap(queue2);

Or alternatively:

swap(queue1, queue2);

Parameters:

  • queue2: The other queue whose contents are to be swapped.

Return value:

.swap() does not return a value.

Example

This example demonstrates the usage of the .swap() method with string queues:

#include <iostream>
#include <queue>
using namespace std;
int main() {
// Declare queues
queue<string> hello;
queue<string> world;
// Populate queues
hello.push("hello");
world.push("world");
// Swap the values of the queues
hello.swap(world);
// Print queue values
cout << hello.front() << " " << world.front();
}

The expected output would be:

world hello

Codebyte Example

The following codebyte example below uses .swap() on two integer queues:

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