C++ Standard Library C++ STL Library

C++ <stack> - swap() Function



The C++ <stack> swap() function is used to exchange all elements of one stack with all elements of another stack. To apply this function, the data-type of both stacks must be same, although the size may differ.

Syntax

template <class T, class Container>
  void swap (stack<T,Container>& lhs, 
             stack<T,Container>& rhs) 
             noexcept(noexcept(lhs.swap(rhs)));

Parameters

lhs First stack.
rhs Second stack.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the swap() function is used to exchange all elements of stack stk1 with all elements of stack stk2.

#include <iostream>
#include <stack>
using namespace std;
 
int main (){
  stack<int> stk1, stk2;

  //add new elements in the stk1
  stk1.push(10);
  stk1.push(20);
  stk1.push(30);
  stk1.push(40);
  stk1.push(50);

  //add new elements in the stk2
  stk2.push(5);
  stk2.push(55);
  stk2.push(555);

  swap(stk1, stk2);

  cout<<"After Swapping, The stk1 contains:";
  while (!stk1.empty()) {
    cout<<" "<<stk1.top();
    stk1.pop();
  }
  
  cout<<"\nAfter Swapping, The stk2 contains:";
  while (!stk2.empty()) {
    cout<<" "<<stk2.top();
    stk2.pop();
  }
  return 0;
}

The output of the above code will be:

After Swapping, The stk1 contains: 555 55 5
After Swapping, The stk2 contains: 50 40 30 20 10

❮ C++ <stack> Library