Stack
Lesson 10 of 23 in Coddy's C++ - Standard Template Library course.
In this chapter you'll learn about container adaptors. The ones you'll learn are the stack, queue and priority-queue.
The C++ Stack is a data structure that is based on the LIFO (Last in-First out) principle. This means that the elements that are added last in the stack data structure will be removed first, and the first element that were added to the stack can be accessed last (This is very similar to stacking plates, or pancakes. When you stack plates, you can't get the plate that's and the bottom and was added first, you need to get the last plate at the top).

stack<dataType> stackName;In order to create a stack in C++, we first need to include the stack header file at the top of the C++ file with #include <stack>.
Then we can declare a stack variable as shown below.
stack<int> number_stack = {1, 2, 3};So, how do we add elements to the stack? - We use the push() method.
stack<int> number_stack;
number_stack.push(1);
number_stack.push(2);
...Like this, we can add new elements to the stack.
Also, we need display elements to the screen. We do that using the top() method, which returns the last value on the top of the stack.
cout << number_stack.top();Output:
2But, now if we keep outputting top() to the screen we'll keep getting the last elements, in this case 2. So we need a method on how to remove an element from the top. For that we use the pop() method, which removes the last element on the top of the stack.
cout << number_stack.top() << endl;
number_stack.pop();
cout << number_stack.top();Output:
2
1In conclusion, the stack data structure is very useful in C++ and in coding and competitive programming in general. It's key component is that it uses the Last in-First out principle.
Stack Methods
| Method | Functionality |
size() | Returns the number of elements in the stack |
empty() | Returns true if the stack is empty, false otherwise |
swap() | Swaps the contents of one stack, with another |
Challenge
EasyYou're given a number N from input. In the next N lines there is one number.
Using a stack, output every number that was entered, but starting from the last number and going backwards.
Input
5
1
2
3
4
5Output
5
4
3
2
1Try it yourself
#include <stack>
#include <iostream>
using namespace std;
int main()
{
// Enter your code here
return 0;
}