Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, Where insertion and deletion is always performed at the top of the stack.
For creating a stack, we must include the <stack> header file in our code. We then use this syntax to define the std::stack:
Syntax:
stack<object_type> stack_name;
Functions of stack:
- empty : Test whether container is empty (public member function )
- size : Return size (public member function )
- top : Access next element (public member function )
- push : Insert element (public member function )
- emplace : Construct and insert element (public member function )
- pop : Remove top element (public member function )
- swap : Swap contents (public member function )
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
s.push(21);
s.push(22);
s.push(24);
s.push(25);
s.pop();
s.pop();
while (!s.empty()) {
cout << ' ' << s.top();
s.pop();
}
}
/*
Output :
22 21
*/
Code Explanation:
- Include the iostream and stack header file or only <bits/stdc++.h> in our code to use its functions.
- Include the std namespace in our code to use its classes without calling it.
- Call the main() function. The program logic should be added within this function.
- Create a stack to store integer values.
- Use the push() function to insert the value 21, 22, 24, 25 into the stack.
- Use the pop() function to remove the top element from the stack, that is, 25. The top element now becomes 24.
- Use the pop() function to remove the top element from the stack, that is, 24. The top element now becomes 22.
- Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.
- Printing the current contents of the stack on the console.
- Call the pop() function on the stack.
- End of the the while loop and main() function.