C++ STL Stack

C++C++Beginner
Practice Now

Introduction

In this lab, we will learn how to create and manipulate a Stack data structure in C++. We will be using the STL (Standard Template Library) provided by C++ to create the stack object.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") subgraph Lab Skills cpp/output -.-> lab-96226{{"`C++ STL Stack`"}} cpp/comments -.-> lab-96226{{"`C++ STL Stack`"}} cpp/variables -.-> lab-96226{{"`C++ STL Stack`"}} cpp/data_types -.-> lab-96226{{"`C++ STL Stack`"}} cpp/operators -.-> lab-96226{{"`C++ STL Stack`"}} end

Create a C++ file

First, let's create a main.cpp file in the ~/project directory using the following command:

touch ~/project/main.cpp

Include header files

We need to include the necessary header files for stack creation and manipulation. The following code will include the required header files:

#include <iostream>
#include <stack> // header file for creating stack

Create a stack object

We can create a stack object using the stack template provided by the STL. We will use the following code to create an integer stack:

std::stack<int> stack;

Note: We created an integer stack here. You can create any type of stack object.

Push elements into the Stack

To push elements to the stack, we use the push() method. The following code pushes elements to the Stack:

stack.push(10);
stack.push(20);
stack.push(30);

Pop elements from the Stack

We can remove elements from the top of the stack using the pop() method. The following code removes the top element from the Stack:

stack.pop();

Check the topmost element

To check the topmost element of the stack, we use the top() method. The following code checks the topmost element of the Stack:

std::cout << stack.top();

To compile and run the code, use the following command in the terminal:

g++ main.cpp -o main && ./main

Summary

In this lab, we created and manipulated a Stack data structure in C++. We used the STL stack template provided by C++ to create a Stack object. We pushed and popped elements from the Stack and checked the topmost element of the Stack using methods such as push(), pop(), and top().

Other C++ Tutorials you may like