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
[Link]("Red");
[Link]("Orange");
cout << "Stack: ";
// print elements of stack
while(![Link]()) {
cout << [Link]() << ", ";
[Link]();
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
[Link]("Red");
[Link]("Orange");
[Link]("Blue");
cout << "Initial Stack: ";
// print elements of stack
display_stack(colors);
// removes "Blue" as it was inserted last
[Link]();
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(![Link]()) {
cout << [Link]() << ", ";
[Link]();
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
[Link]("Red");
[Link]("Orange");
[Link]("Blue");
// get top element
string top = [Link]();
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 ([Link]()) {
cout << "Yes" << endl;
else {
cout << "No" << endl;
cout << "Pushing elements..." << endl;
// push element into the stack
[Link](2.3);
[Link](9.7);
cout << "Is the stack empty? ";
// check if the stack is empty
if ([Link]()) {
cout << "Yes";
else {
cout << "No";
return 0;