≡ Menu

3 Example Programs to Understand C++ STL Stack Implementation

What is a stack?

In our daily life, we may see several items in a stack. For example: stack of dishes, pancakes stacked on a plate, stones on a stick for Hanoi tower problem, stack of chairs, stack of books, etc.

In programming language, stack is a data structure that has few interesting properties. Its elements are added as you get them, and you empty the stack from last element that you have added into it.

Stack is also known as LIFO, which stands for “Last In First Out”.

So, the first added element gets out last and the last added member gets out first. The structure is good in some typical programming situations that could occur very often in software development or software related topic, as well as hardware implementations.

Stack Implementation Strategies

For a stack, there are a few possible implementations, the most usual classification is based on predicted size of the stack, we are using. The following are three most-common implementation strategy for a stack:

  1. * The first one, is called stack of limited size, and usually gets implemented with array and a counter that know how many elements you have added, also you would need to know the capacity, as well.
  2. * The second one is more interesting, and it is implemented with: struct and pointers. It is sometimes called stack of “unknown size”. Both the first and second option can be used in both C and C++ programming language.
  3. * The third possible solution is to create your own class or template class, with few methods and overloaded operators, friend methods etc…

It is also possible to have stack of objects and pointers to objects too. But, the focus of our article will be on STL stack.

Refer to this: Introduction to C++11 and C++14 with Example Code Snippet

How to use STL Stack?

In order to use STL stack, first you need to add “#include stack” at the beginning of your code.

This will enable you to use stack in your program. To be more precise, it is STL container, and it is implemented with some other STL data structure, which makes it an adapter.

After this, you would need to declare stack of some type, that could be done like this:

stack nameOfOurStack;

After you have declared stack you could apply few member functions.

If you need to check if your stack is empty, you could use empty member function that will return true or false, according to state of your stack. To use this, you could write it like this:

nameOfOurStack.empty();

When you need to figure out the size of stack, you could create counter, and if you add the elements you increment the counter or if you remove elements from stack you decrement your counter. This should be done with size, that is public member function right there. This is shown below:

nameOfOurStack.size();

Now obtained elements that have been added on the stack, could be used in your program, according to your needs.

To access the top of our stack, you would use top, which will copy element from top of our stack, however it will not remove them from the container as you might expect in the beginning.

nameOfOurStack.top();

And if you would like to remove the element from top of stack, you have pop.

nameOfOurStack.pop();

In faze of creating the stack you: get elements from user, read them from file or perhaps calculate them. To add one more element on top of the stack you code it like this:

nameOfOurStack.push(someElement);

In C++ 11 you should have emplace also. It will construct and add the element to stack. For example you could do something like this:

nameOfOurStack.emplace("Some string that will be added to stack of strings");

If you would like to swap two stacks, since C++ 11 you should have swap as well.

You might also need few relational operators that could be very useful, if you are trying to compare two stacks.

STL Stack Example Program #1

Our first example will illustrate how to create stack of few integers and how to perform few basic operations on it.

#include <iostream>
#include <stack>

using namespace std;

int
main()
{
stack<int> nStack;

cout<<"NOW YOU HAVE STACK !!!"<<endl;

cout<<"The size is="
<<nStack.size()<<endl;
cout<<"The stak ";
(nStack.empty()==true)?cout<<" is " : cout<<" it is not ";
cout<<" empty "<<endl;

cout<<"\n\nNOW YOU ADD TWO INT-S TO IT!!!"<<endl;

nStack.emplace(1);
nStack.push(2);
cout<<"The size is="
<<nStack.size()<<endl;
cout<<"The stack ";
(nStack.empty()==true)?cout<<" is " : cout<<" it is not ";
cout<<" empty "<<endl;

int nElement =nStack.top();
cout<<"The size is="
<<nStack.size()<<endl;
cout<<"The stack ";
(nStack.empty()==true)?cout<<" is " : cout<<" it is not ";
cout<<" empty "<<endl;

cout<<"\n\nWE HAVE TAKEN TOP ELEMENT!!!"<<endl;
nStack.pop();
cout<<"The size is="
<<nStack.size()<<endl;
cout<<"The stack ";
(nStack.empty()==true)?cout<<" is " : cout<<" it is not ";
cout<<" empty "<<endl;

nStack.pop();

return EXIT_SUCCESS;
}

STL Stack Example Program #2

Our second example will explain how to create stack of strings.

#include <iostream>
#include <stack>
#include <string>

using namespace std;
int
main()
{
stack<string> sStack;

for(;;)
{
 char cPick;
 cout<<"Would you like to add new string y/n->";
 cin>>cPick;
 if(cPick=='n') break;

 cout<<"Next string plase->";
 string sTemp;
 cin>>sTemp;
 sStack.emplace(sTemp);
 cout<<endl;
}

while(!sStack.empty())
{
 //YES, AND NEGATION WILL TAKE SOME TIME!
 string sTemp;
 //FIRST WE TAKE COPY AND THEN WE TAKE FROM TOP OF THE STRING
 sTemp=sStack.top(); sStack.pop();
 cout<<sTemp<<endl;
}

return EXIT_SUCCESS;
}

STL Stack Example Program #3

Third and final example will show you how to convert the decade number into its binary equivalent.

#include <iostream>
#include <stack>

typedef unsigned long long int myType;

using namespace std;

int
main()
{

cout<<"WE WILL CONVERT NUMBER INTO BINARY EQUIVALENT"<
//PREPARE SPACE FOR NUMBER WE INPUT
myType temp;
cout<<"Please, input the number->";
cin>>temp;

//LET'S DECLARE STACK
stack <int> nBinaryNumber;

//FIND BINARY CIPHERS
while(temp)
{
 int nCipher = temp%2;
 nBinaryNumber.emplace(nCipher);
 temp/=2;
}

//PRESENT THE STACK
while(!nBinaryNumber.empty())
{
 (nBinaryNumber.top()==1)?cout<<'1':cout<<'0';
 nBinaryNumber.pop();
}

return EXIT_SUCCESS;
}

Additional Exercises

After you have read this article and adopted the ideas presented, it might be useful if you learn few more class templates from STL: queue, list, map, deck, vector, etc. This is a good reference: STL Tutorial: How to use C++ Vector with Example Program

For practice, you can also develop your own stack, with few overloaded methods and few unusual methods, that might be useful for problem that you are solving. For example, you might need to place elements not at the top but at certain position of stack.

The following are few additional exercises that you can sole using stack:

  1. Get string input from user, and use stack to write it backwards.
  2. Get number input from user, and use stack to write it backwards.
  3. Broaden our example so that you could handle non whole numbers as well.
  4. Create stack for Hanoi tower problem, and solve it with stack.
  5. Simulate recursion for n!
  6. Create calculator that will implement reverse polish notation.
  7. Try to create your own class and add few methods that are not covered in STL stack.

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 0 comments… add one }

Leave a Comment