C++ Deque swap() Function

Last Updated : 13 May 2026

In C++, the deque::swap() function is used to exchange the contents of one deque with another deque. After swapping, the elements of both deques are interchanged without changing their original types. This function is useful for exchanging data between containers. The swap() function works only when both deques are of the same data type.

C++ Deque swap() Function

Syntax

It has the following syntax:

Or

Parameters

  • second: It is another deque container whose content is to be swapped with the given deque.
  • Deque1 & Deque2: It is the deque names that need to be swapped with deque2.

Return Value

It does not return any value.

Examples of deque swap() function

Here, we are going to discuss several examples that demonstrate deque swap() function.

Example 1: Swap the Contents of Two String Deques Using swap()

This example demonstrates how to exchange the contents of two string deques using the swap() function.

Output:

After swapping, value of str is: java is a programming language
After swapping, value of str1 is: C++ is a programming language

Explanation:

In this example, we initialized two deques, str and str1, that are initialized with different string values. After that, we use the swap() function to exchange their contents. Two iterators are created to traverse each deque using the begin() method, and the elements are printed after swapping. As a result, the contents of str and str1 are interchanged, and now str contains "java is a programming language" and str1 contains "C++ is a programming language".

Example 2: Attempt to Swap Deques of Different Data Types Using swap()

This example demonstrates what happens when the swap() function is used with deques of different data types.

Output:

error: no matching function for call to 'std::deque::swap(std::deque&)

Explanation:

In this example, we have initialized two deques 'c' that have char values, and another one is deque 's' that has int type of values. After that, we have performed the swapping of the deques with each other using the swap() method. Finally, we returned 0 as the last statement. In the output, we could see that the swap() function throws an error as the types of both the deques are different. Therefore, if we want to perform swapping of the elements, we should have deques of the same type.

Example 3: Swap Two Integer Deques Using swap()

This example demonstrates how to swap the contents of two integer deques using the swap() function.

Output:

Content of first deque:10 20 30 40 50
Content of second deque:1 2 3 4

Explanation:

In this example, we have taken two integer deques, first and second, that are initialized with different values. After that, we use the swap() function to exchange their contents. Next, we use an iterator to traverse and display the elements of each deque using a for loop. As shown in the output, the contents of both deques are successfully swapped.


Next TopicC++ Deque