C++ program to demonstrate empty() and swap() function on stack container of STL














































C++ program to demonstrate empty() and swap() function on stack container of STL



swap() : This function would swap the elements of one stack with the elements of another stack.
Data type of elements and size of stacks should be same.
Syntax : first_stack.swap(second_stack)
empty() : This function would return true if stack is empty.
syntax : stack_name.empty()


PROGRAM:
#include<iostream>
//header of the container should be included
#include<stack>
using namespace std; int main()
{
stack<int> stack1;
stack<int> stack2;
//push function adds the passed value to the top of the stack
stack1.push(9); stack1.push(10); stack1.push(1); stack1.push(3); stack1.push(4);
//size() function would return number of elements in the stack
cout<<"number of elements in the first stack is "<<stack1.size()<<endl; stack2.push(22); stack2.push(33); stack2.push(44); stack2.push(55); stack2.push(66); cout<<"number of elements in the second stack is "<<stack2.size()<<endl; cout<<"After swap:"<<endl; stack1.swap(stack2); cout<<"elements in the first stack are "<<endl;
int n=stack1.size();
for(int i=1;i<=n;i++)
{ int j=stack1.top(); stack1.pop();
cout<<j<<" "<<endl;
} cout<<"elements in the second stack are "<<endl;
int n1=stack2.size();
for(int i=1;i<=n1;i++) { int j=stack2.top(); stack2.pop(); cout<<j<<" "<<endl;
}
cout<<"after implementing pop function on both the stacks"<<endl;
if(stack1.empty())
cout<<"first stack is empty "<<endl;
if(stack2.empty())
cout<<"second stack is also empty"<<endl; return 0; }

OUTPUT:
number of elements of first stack is 5
number of elements of second stack is 5
After swap:
elements in the first stack are
66
55
44
33
22
elements in the second stack are
4
3
1
10
9
after implementing pop function on both the stacks
first stack is empty
second stack is also empty

Comments