Add Element Into the Stack
We use the push() method to add an element into a stack.
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of strings
stack<string> colors;
// push elements into the stack
colors.push("Red");
colors.push("Orange");
cout << "Stack: ";
// print elements of stack
while(!colors.empty()) {
cout << colors.top() << ", ";
colors.pop();
return 0;
Remove Elements From the Stack
We can remove an element from the stack using the pop() method.
#include <iostream>
#include <stack>
using namespace std;
// function prototype for display_stack utility
void display_stack(stack<string> st);
int main() {
// create a stack of strings
stack<string> colors;
// push elements into the stack
colors.push("Red");
colors.push("Orange");
colors.push("Blue");
cout << "Initial Stack: ";
// print elements of stack
display_stack(colors);
// removes "Blue" as it was inserted last
colors.pop();
cout << "Final Stack: ";
// print elements of stack
display_stack(colors);
return 0;
// utility function to display stack elements
void display_stack(stack<string> st) {
while(!st.empty()) {
cout << st.top() << ", ";
st.pop();
cout << endl;
Access Elements From the Stack
We access the element at the top of the stack using the top() method.
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of strings
stack<string> colors;
// push element into the stack
colors.push("Red");
colors.push("Orange");
colors.push("Blue");
// get top element
string top = colors.top();
cout << "Top Element: " << top;
return 0;
Get the Size of the Stack
We use the size() method to get the number of elements in the stack .
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of int
stack<int> prime_nums;
// push elements into the stack
prime_nums.push(2);
prime_nums.push(3);
prime_nums.push(5);
// get the size of the stack
int size = prime_nums.size();
cout << "Size of the stack: " << size;
return 0;
Check if the Stack Is Empty
We use the empty() method to check if the stack is empty. This method
returns:
1 (true) - if the stack is empty
0 (false) - if the stack is not empty
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of double
stack<double> nums;
cout << "Is the stack empty? ";
// check if the stack is empty
if (nums.empty()) {
cout << "Yes" << endl;
else {
cout << "No" << endl;
cout << "Pushing elements..." << endl;
// push element into the stack
nums.push(2.3);
nums.push(9.7);
cout << "Is the stack empty? ";
// check if the stack is empty
if (nums.empty()) {
cout << "Yes";
else {
cout << "No";
return 0;