stack::swap() method

In C++, the standard library gives us the facility to use stacks as a type of container adaptors with LIFO type of working. The stack::swap() is a C++ Standard Library method which exchanges the contents of two stacks (of the same type)

Syntax:

s1_name.swap(s2_name);

Parameters: The stack::swap() method accepts a single parameter:
•Another stack of the same type (sizes may differ)
Return value: none

Example of stack::swap() method

#include <iostream>
#include <stack>
using namespace std;
void prints(stack<int> s)
{
  while(!s.empty())
  {
    cout<<s.top()<<"  ";
    s.pop();
  }
  cout<<endl;
}
int main() 
{
  stack<int> s1;
  s1.push(1);
  s1.push(2);
  s1.push(3);
  s1.push(4);

  stack<int> s2;
  s2.push(10);
  s2.push(11);
  s2.push(12);
  cout<<"S1 before swap: \n";
  prints(s1);
  cout<<"S2 before swap: \n";
  prints(s2);
  s1.swap(s2);
  cout<<"S1 after swap: \n";
  prints(s1);
  cout<<"S2 after swap: \n";
  prints(s2);
}

Output:

S1 before swap:
4 3 2 1
S2 before swap:
12 11 10
S1 after swap:
12 11 10
S2 after swap:
4 3 2 1

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top