Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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

template <class T, class Alloc>
void swap (deque<T,Alloc>& lhs, 
           deque<T,Alloc>& rhs);
template <class T, class Alloc>
void swap (deque<T,Alloc>& lhs, 
           deque<T,Alloc>& rhs);

Parameters

lhs First deque.
rhs Second deque.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

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

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

  deque<int>::iterator it;

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

  swap(Mydq1, Mydq2);

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

  return 0;
}

The output of the above code will be:

Before Swapping, The Mydq1 contains: 10 20 30 40 50
Before Swapping, The Mydq2 contains: 5 55 555

After Swapping, The Mydq1 contains: 5 55 555
After Swapping, The Mydq2 contains: 10 20 30 40 50

❮ C++ - Deque