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.

It has the following syntax:
Or
It does not return any value.
Here, we are going to discuss several examples that demonstrate deque swap() function.
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".
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.
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.
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India