C++ .swap()
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.
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 queuesqueue<string> hello;queue<string> world;// Populate queueshello.push("hello");world.push("world");// Swap the values of the queueshello.swap(world);// Print queue valuescout << hello.front() << " " << world.front();}
The expected output would be:
world hello
Codebyte Example
The following codebyte example below uses .swap() on two integer queues:
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