What is std::stack?

A stack is a data structure that operates based on LIFO (Last In First Out) technique. The std::stack allows elements to be added and removed from one end only.

The std::stack class is a container adapter. Container objects hold data of a similar data type. You can create a stack from various sequence containers. If no container is provided, the deque containe will be used by default. Container adapters don't support iterators, so it can't be used to manipulate data.

In this C++ tutorial, you will learn

Stack Syntax

To create a stack, we must include the <stack> header file in our code. We then use this syntax to define the std::stack:

template <class Type, class Container = deque<Type> > class stack;
  • Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type.
  • Container – is the Type of underlying container object.

Member Types

Here are stack member types:

  • value_type- The first template parameter, T. It denotes the element types.
  • container_type- The second template parameter, Container. It denotes the underlying container type.
  • size_type- Unsigned integral type.

Operations in Stack

A C++ stack supports the following basic operations:

  • push – It adds/pushes an item into the stack.
  • pop – It removes/pops an item from the stack.
  • peek – Returns the top item of the stack without removing it.
  • isFull – Checks whether a stack is full.
  • isEmpty – Checks whether a stack is empty.

Stack Implementation

Step 1) We initially have an empty stack. The top of an empty stack is set to -1.

Step 2) Next, we have pushed the element 5 into the stack. The top of the stack will points to the element 5.

Step 3) Next, we have pushed the element 50 into the stack. The top of the stack shifts and points to the element 50.

Step 4) We have then performed a pop operation, removing the top element from the stack. The element 50 is popped from the stack. The top of the stack now points to the element 5.

push() and pop()

The stack::push() functions adds new item to the top of stack. The stack size is increased by a 1 after the insertion. The function takes this syntax:

stack.push(value)

The value is the item to insert into the stack.

The stack:: pop() function removes the top element of the stack. This is the newest item of the stack. The stack size is reduced by 1 after the removal. Here is the function syntax:

stack.pop()

The function takes no parameters.

Example 1:

#include <iostream> 
#include <stack> 
using namespace std;
int main() {
	stack<int> st;
	st.push(10);
	st.push(20);
	st.push(30);
	st.push(40);
	
         st.pop();
	st.pop();

	while (!st.empty()) {
		cout << ' ' << st.top();
		st.pop();
	}
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the stack header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the main() function. The program logic should be added within this function.
  5. Create a stack st to store integer values.
  6. Use the push() function to insert the value 10 into the stack.
  7. Use the push() function to insert the value 20 into the stack.
  8. Use the push() function to insert the value 30 into the stack.
  9. Use the push() function to insert the value 40 into the stack.
  10. Use the pop() function to remove the top element from the stack, that is, 40. The top element now becomes 30.
  11. Use the pop() function to remove the top element from the stack, that is, 30. The top element now becomes 20.
  12. Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.
  13. Printing the current contents of the stack on the console.
  14. Call the pop() function on the stack.
  15. End of the body of the while loop.
  16. End of the main() function body.

empty(), size(), top()

Stacks have inbuilt functions that you can use to play around with the stack and its values. These include:

  • empty()- checks whether a stack is empty or not.
  • size()- returns the size of stack, that is, number of elements in a stack.
  • top()- accesses stack element at the top.

Example 2:

#include <iostream> 
#include <stack>  
using namespace std;
void createStack(stack <int> mystack)
{
	stack <int> ms = mystack;
	while (!ms.empty())
	{
		cout << '\t' << ms.top();
		ms.pop();
	}
	cout << '\n';
}
int main()
{
	stack <int> st;
	st.push(32);
	st.push(21);
	st.push(39);
	st.push(89);
	st.push(25);

	cout << "The stack st is: ";
	createStack(st);
	cout << "\n st.size() : " << st.size();
	cout << "\n st.top() : " << st.top();
	cout << "\n st.pop() : ";
	st.pop();
	createStack(st);
	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our code in order to use its functions.
  2. Include the stack header file in our code in order to use its functions.
  3. Include the std namespace in our program in order to use its classes without calling it.
  4. Create the function createStack that we can use to create the stack mystack. The stack will hold a set of integers.
  5. The beginning of the body of the createStack function.
  6. Create an instance of the mystack datatype and giving it the name ms.
  7. Use the while loop and the empty() function to check whether the stack is empty.
  8. The start of the body of the while loop.
  9. Use the top() function stored at the top of the stack. The \t character will create a new tab.
  10. Use the pop() function to delete the element at the top of the stack.
  11. End of the body of the while loop.
  12. Print a blank line on the console.
  13. End of the body of the createStack function.
  14. Call the main() function. The program logic should be added within the body of the main() function.
  15. The start of the body of function main().
  16. Create a stack object st.
  17. Use the push() function to insert the element 32 into the stack.
  18. Use the push() function to insert the element 21 into the stack.
  19. Use the push() function to insert the element 39 into the stack.
  20. Use the push() function to insert the element 89 into the stack.
  21. Use the push() function to insert the element 25 into the stack.
  22. Print some text on the console.
  23. Call the createStack function to execute the above insert operations into the stack.
  24. Print the size of the stack on the console alongside other text.
  25. Print the element at the top of the stack on the console.
  26. Print some text on the console.
  27. Delete the element at the top of the stack. It will then return the elements remaining in the stack.
  28. Call the createStack function to execute the above operations.
  29. The program must return value upon successful completion.
  30. End of the body of function main().

emplace() and swap()

These are other inbuilt stack functions:

  • emplace()- constructs then inserts new element to top of stack.
  • swap()- exchanges stack contents with another stack's contents.

Example 3:

#include <iostream>    
#include <stack>
#include <cstdlib>
using namespace std;
int main() {
	stack<int> st1;
	stack<int> st2;

	st1.emplace(12);
	st1.emplace(19);

	st2.emplace(20);
	st2.emplace(23);

	st1.swap(st2);

	cout << "st1 = ";
	while (!st1.empty()) {
		cout << st1.top() << " ";
		st1.pop();
	}

	cout << endl << "st2 = ";
	while (!st2.empty()) {
		cout << st2.top() << " ";
		st2.pop();
	}
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the stack header file in our code to use its functions.
  3. Include the cstdlib header file in our code to use its functions.
  4. Include the std namespace in our code to use its classes without calling it.
  5. Call the main() function. The program logic will be added within the body of this function.
  6. Declare a stack named st1 to store integer values.
  7. Declare a stack named st2 to store integer values.
  8. Use the emplace() function to insert the integer 12 into the stack named st1.
  9. Use the emplace() function to insert the integer 19 into the stack named st1.
  10. Use the emplace() function to insert the integer 20 into the stack named st2.
  11. Use the emplace() function to insert the integer 23 into the stack named st2.
  12. Use the swap() function to swap the contents of the two stacks, st1 and st2. The contents of the stack st1 should be moved to the stack st2. The contents of the stack st2 should be moved to the stack st1.
  13. Print some text on the console.
  14. Use the while statement and the empty() function to check whether the stack st1 is not empty.
  15. Print the contents of the stack st1 on the console. The " " adds space between the stack elements when printing them on the console.
  16. Execute the pop() function on the stack st1 to remove the top element.
  17. End of the body of the while statement.
  18. Print some text on the console. The endl is a C++ keyword for end line. It moves the mouse cursor to the next line to begin printing from there.
  19. Use the while statement and the empty() function to check whether the stack st2 is not empty.
  20. Print the contents of the stack st2 on the console. The " " adds space between the stack elements when printing them on the console.
  21. Execute the pop() function on the stack st2 to remove the top element.
  22. End of the body of the while statement.
  23. End of the body of the main() function.

Stack in STL

The STL (Standard Template Library) comes with template classes that provide common C++ data structures. Therefore, a stack can also be implemented in STL. We simply include this library in our code and use it to define a stack.

stack<T> st; 

The above syntax declares a stack st to elements of data type T.

Example 3:

#include <iostream>      
#include <stack>
#include <cstdlib>
using namespace std;
int main() {
	stack<int> st;
	st.push(12);
	st.push(19);
	st.push(20);
	cout << st.top();   
	cout << st.size();  
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the stack header file in our code to use its functions.
  3. Include the cstdlib header file in our code to use its functions.
  4. Include the std namespace in our code to use its classes without calling it.
  5. Call the main() function. The program logic should be added within the body of this function.
  6. Declare a stack st to store integer data.
  7. Add the element 12 to the stack.
  8. Add the element 19 to the stack.
  9. Add the element 20 to the stack.
  10. Print the element at the top of the stack on the console.
  11. Print the size of the stack on the console.
  12. End of the body of the function main().

Summary:

  • A stack is a data structure that operates based on the LIFO (Last In first Out) technique.
  • The std::stack only allows items to be added and removed from one end.
  • The std::stack class is a container adapter, holding items of a similar data type.
  • A stack can be created from various sequence containers.
  • If you don't provide a container, the deque container will be used by default.
  • The push() function is for inserting items into the stack.
  • The pop() function is for removing the top item from the step.
  • The empty() function is for checking whether a stack is empty or not.

 

YOU MIGHT LIKE: