C++ .swap()
Published Oct 28, 2025
Contribute to Docs
The .swap() method exchanges the contents of one deque with another deque of the same type. After the swap, each deque holds the elements that were originally in the other.
Syntax
deque1.swap(deque2);
Parameters:
deque2: The deque whose contents will be exchanged withdeque1.
Return value:
This method does not return a value.
Example
This example demonstrates swapping the contents of two integer deques using .swap():
#include <iostream>#include <deque>using namespace std;int main() {deque<int> deque1 = {1, 2, 3};deque<int> deque2 = {10, 20, 30, 40};cout << "Before swap:" << endl;cout << "Deque 1: ";for (int num : deque1) cout << num << " ";cout << endl;cout << "Deque 2: ";for (int num : deque2) cout << num << " ";cout << endl;deque1.swap(deque2);cout << "\nAfter swap:" << endl;cout << "Deque 1: ";for (int num : deque1) cout << num << " ";cout << endl;cout << "Deque 2: ";for (int num : deque2) cout << num << " ";cout << endl;return 0;}
The output of this code is:
Before swap:Deque 1: 1 2 3Deque 2: 10 20 30 40After swap:Deque 1: 10 20 30 40Deque 2: 1 2 3
Codebyte Example
This example swaps the contents of two deques containing strings:
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