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
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 example below, the 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; swap(dq1, 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