C++ .swap()

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

  • 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

deque1.swap(deque2);

Parameters:

  • deque2: The deque whose contents will be exchanged with deque1.

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 3
Deque 2: 10 20 30 40
After swap:
Deque 1: 10 20 30 40
Deque 2: 1 2 3

Codebyte Example

This example swaps the contents of two deques containing strings:

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