Stacks in STL - C++

We all remember stacking up assignments on our teacher’s desk where we used to keep our assignment on the top of all other assignments already present on the desk. The correction was done by taking the topmost assignment from the stack, which meant that the last submitted assignment was the first one to be corrected.

We can find various other real life examples similar to this. This approach is termed as the LIFO approach i.e. Last in first out approach, where we perform various functions starting from the newest entry to the sequence.

Stack data structure is an implementation of LIFO approach, where insertion, deletion and traversal of the sequence is done from the topmost element of the sequence.

Insertion : element is inserted at the top of the stack

Deletion : element is deleted from top of the stack

Traversal : elements are traversed in the reverse sequence of their insertion i.e. the last entered element will be the first to be displayed.

For insertion and deletion we will use the push and pop function respectively.

To display the content of the stack we will use peek function.

Implementation of STL stack :



Size of first_stack is 0

Size of second_stack is 5

Size of third_stack is 4

Oops stack is empty

top-most element of first_stack is 50

50 is deleted from top of the first_satck

Size of first_stack before popping the elements 4

40 30 20 10

Size of first_stack after popping the elements 0

So that’s it for this article we will be coming up with our next article very soon till then keep learning, keep coding, keep reading and keep improving !!

Happy Coding 😊

By Programmers Army