Stack - STL Container class
CoderSource.net
Stack - STL Container class - Article by consulttoday
Level: BeginnerType: Article
Rating: Page: 2 of 2

Date: 1/20/2006 12:00:00 AM

Environment: C++, Unix, Windows

pop()

This method is used for popping up the last added (MRA : Most Recently Added) element of the stack.

The difference  between top() and pop() is that in top() we are not really popping the MRA element but the pop() method pops the most recently added Element. Here is a code involving push(), pop() and top()

 

#include <iostream>
#include <stack>

using namespace std;

int main()
{
string title;
int howmany;


stack<string> discs;
//Asking the user how many discs he wants to enter in the stack.
//The loop will rotate that many number of times and then 
//prompt the user for input.
cout<<"How many discs :";
cin>>howmany;

for(int i=0;i>title;
//pushing the discs one upon the other
discs.push(title);
}

cout<<"Now at the top of the CD Stack we have :"<<discs.top()<<endl;
cout<<"The first one entered is "<<endl;
while(!discs.empty())
{
title = discs.top();
discs.pop();
}
cout<<title<<endl;
return 0;
}

 

Here is the screenshot of a sample run of the above program

To get the Maximum Possible Size of the Stack

To find the maximum possible size of the stack we first have to get the allocator that is associated with the stack and then we shall have to use max_size() method to find the maximum possible size of the specified stack.

#include <iostream>
#include <stack>

using namespace std;
{
stack<string> discs;
cout<<discs.get_allocator().max_size()<<endl;
return 0; 
}

The output of this program is 
268435455
-----------------------

This is independant of the size of the stack. And it is a variable constant. That means for a stack of integer this value will be different, for a float stack this value will be different from integer stack but will be constant for all float type variables.

Applications

Stacks are used frequently in parsers. Very common examples includes "Infix to Postfix conversion", "Parenthesis Matching", "Back Tracking (Mostly in Games Programming)" etc..We will take up all these examples in the next article.. Till then happy coding...

1 2

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us