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.
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.
First, let's create a main.cpp
file in the ~/project
directory using the following command:
touch ~/project/main.cpp
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
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.
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);
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();
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
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()
.