Stack in C++ STL (Standard Template Library)

C++ STL Stack: Here, we are going to learn about the stack in C++ STL, how to implement a stack using C++ standard template library?
Submitted by Radib Kar, on February 03, 2019

Stack in data structure

The stack is an ordered list where insertion and deletion are done from the same end, top. The last element that entered first is the first one to be deleted (the basic principle behind the LIFO). That means it is a data structure which is implemented as LIFO.

The main stack operations are (basic ADT operations):

  1. push (T data): Insertion at top
  2. T pop(): Deletion from top
  3. bool isEmpty(): Checks for stack to be empty

Here, T is the datatype (int/char/float etc)

STL

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. Therefore STACK can be implemented with help of STL too.

STACK in STL

To declare a stack of datatype T:

    stack<T> st; //basic STL declarations
    e.g.: 
    stack<int> st; //stack to hold integers only

To declare the stack iterator:

    stack<T>::iterator it;
    e.g.:
    stack<int>::iterator it;

C++ STACK functions

push(T item) - Inserts an item on top

pop() - Pops the top element, it doesn’t return the popped item

top() - Returns the top element

empty - Returns true or false based on whether stack is empty

size() - Returns size of the stack

You can click on each function to check detailed code and implementation of each function. Below is the assemble of a total stack operation.

C++ stack implementation

#include <bits/stdc++.h>
using namespace std;

int main(){
	cout<<"...STACK STL...\n";
	stack<int> st; //declare the stack

	cout<<"enter 0 to stop pushing else enter any other integer\n";
	int num,count=0;
	cin>>num;
	while(num!=0){
		st.push(num); //push function
		cin>>num;
	}
	
	cout<<"stack size is: "<<st.size()<<endl; //size function
	
	cout<<"popping...\n";
	cout<<"stack elements are:\n";
	while(!st.empty()){//stack not empty
		cout<<"top element is:"<<st.top()<<endl;//print top element
		st.pop();
		count++;
	}

	if(st.empty())
		cout<<"stack empty\n";
	
	cout<<"stack size is: "<<st.size()<<endl; //size function
	cout<<count<<" pop operation performed total to make stack empty\n";
	
	return 0;
}

Output

...STACK STL...
enter 0 to stop pushing else enter any other integer
3
7
8
12
-4
0
stack size is: 5
...popping
stack elements are:
top element is:-4
top element is:12
top element is:8
top element is:7
top element is:3
stack empty
stack size is: 0
5 pop operation performed total to make stack empty



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.