C++ Standard Library C++ STL Library

C++ <deque> - swap() Function



The C++ deque::swap function is used to exchange all elements of one deque with all elements of another deque. To apply this function, the data-type of both deques must be same, although the size may differ.

Syntax

void swap (deque& other);
void swap (deque& other);

Parameters

other Specify deque, whose elements need to be exchanged with another deque.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the deque::swap function is used to exchange all elements of deque dq1 with all elements of deque dq2.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<int> dq1{10, 20, 30, 40, 50};
  deque<int> dq2{5, 55, 555};

  deque<int>::iterator it;

  cout<<"Before Swapping, The dq1 contains:";
  for(it = dq1.begin(); it != dq1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nBefore Swapping, The dq2 contains:";
  for(it = dq2.begin(); it != dq2.end(); ++it)
    cout<<" "<<*it;

  dq1.swap(dq2);

  cout<<"\n\nAfter Swapping, The dq1 contains:";
  for(it = dq1.begin(); it != dq1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nAfter Swapping, The dq2 contains:";
  for(it = dq2.begin(); it != dq2.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before Swapping, The dq1 contains: 10 20 30 40 50
Before Swapping, The dq2 contains: 5 55 555

After Swapping, The dq1 contains: 5 55 555
After Swapping, The dq2 contains: 10 20 30 40 50

❮ C++ <deque> Library

5