Stack container in STL in C++














































Stack container in STL in C++



push() : This function would add the passed value to the top of the stack.
Syntax : stack_name.push(number)
pop() : This function would delete the top most element from the stack
Syntax : stack_name.pop()
top() : This function would return the top element from the stack but will not delete it from the stack.
Syntax : stack_name.top()
size() : This function would return the number of elements present in the stack
Syntax : stack_name.size()



PROGRAM:

#include<iostream>
//header of the container should be included
#include<stack>
using namespace std;
int main()
{
stack<int> stack1;
//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 stack are "<<stack1.size()<<endl;
//top() function would return the top most element in the stack but will not delete it
cout<<"top most element is "<<stack1.top()<<endl; //pop() function would delete the top element from the stack
int n=stack1.size(); cout<<"the elements in the stack are "<<endl;
for(int i=1;i<=n;i++)
{
int j=stack1.top();
stack1.pop();
cout<<j<<" ";
}
cout<<"\n";
cout<<"END"<<endl;
return 0;
}

OUTPUT:
number of elements in the stack are 5
top most element is 4
the elements in the stack are
4 3 1 10 9
END

Comments