CPP STL Tutorial : C++ std::stack and it’s operations.

In this chapter we shall learn about:

1. stack introduction.
2. stack operations.
3. stack member declaration.
4. stack member functions

1. stack introduction.

1. stack is a type of container adapter.
2. It supports LIFO [Last In First Out].
3. LIFO means, that the elements are inserted from the top and removed from the top.

Below is the header file to be used for stack:

#include <stack>          // std::stack

2. stack operations.

Stack will support below operations:
empty
size
back
push_back
pop_back

3. stack member declaration.

A stack can be declared as below:
 std::stack<int> mystack;
  mystack.push(10);
  mystack.push(20);

4. stack member functions

empty : It will test whether container is empty
size : It will return size
top : It will access next element
push : It will insert element
pop : It will remove top element
Example:
#include <iostream>
#include <stack>
//for more tutorials on C, C++, STL, DS visit www.ProDeveloperTutorial.com
using namespace std;

int main ()
{
  std::stack<int> mystack;

  mystack.push(10);
  mystack.push(20);
  mystack.push(30);
  mystack.push(40);
  
  cout<<"Size of stack is "<< mystack.size()<<endl;
  cout<<"Popping the elements"<<endl;
   while (!mystack.empty())
  {
     std::cout << ' ' << mystack.top();
      mystack.pop();
  }



  return 0;
}

Output:

Size of stack is 4
Popping the elements
40 30 20 10
Write a Comment

Leave a Comment

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