stack swap() in C++ STL


In this article, we will be discussing the working, syntax, and examples of stack::swap() function in C++ STL.

What is Stack in C++ STL?

Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top or the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack, we then also remove it from the top.

What is stack::swap()?

stack::swap() function is an inbuilt function in C++ STL, which is defined in <stack> header file. swap() is used to swap the contents of the two stacks associated. This function exchanges the contents of the containers

Syntax

stack_name.swap(stack& stack2);

Parameters

The function accepts the following parameter(s) −

  • stack2: Another stack container with whom we want to swap the content.

Return value

This function returns nothing

Input

std::stack<int>odd;
odd.emplace(1);
odd.emplace(3);
odd.emplace(5);
std::stack<int&g; eve;
eve.emplace(2);
eve.emplace(4);
eve.emplace(6);
odd.swap(eve);

Output 

odd: 2 4 6
eve: 1 3 5

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck_1, stck_2;
   //inserting elements to stack 1
   stck_1.push(1);
   stck_1.push(2);
   stck_1.push(3);
   stck_1.push(4);
   //inserting elements to stack 2
   stck_2.push(5);
   stck_2.push(6);
   stck_2.push(7);
   stck_2.push(8);
   //swapping elements of stack 1 in stack 2 and vice-versa
   stck_1.swap(stck_2);
   cout<<"Elements in stack 1 are: ";
   while (!stck_1.empty()){
      cout<<stck_1.top()<<" ";
      stck_1.pop();
   }
   cout<<"\nElements in stack 2 are: ";
   while (!stck_2.empty()){
      cout<<stck_2.top()<<" ";
      stck_2.pop();
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Elements in stack 1 are: 8 7 6 5
Elements in stack 2 are: 4 3 2 1

Updated on: 22-Apr-2020

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements