CPP STL Intro - The Stack
Introduction
This tutorial introduces the concept of the stack data type. An excellent example of a real-world stack can be found at the local grocery store. The cereal box shelf is stocked from the front and customers also remove boxes from the front. The last box stocked by the clerk is the first box grabbed by the next customer. Computer Scientists describe this as "First in First out" or FIFO.
/****************************************************************************** * STL Intro: The Stack main.cpp * * * * Author: nicomp * * * * Abstract: A brief introduction to the Standard Template Library * * * * * * * * The Source: http://www.sgi.com/tech/stl/ * * Other resources: http://www.sgi.com/tech/stl/other_resources.html * * Chapter 22 from our book: http://proquest.safaribooksonline.com.proxy.libraries.uc.edu/9780136085669/ch22#snippet * * The book: http://www.wwnorton.com/catalog/fall99/newnewthing.htm * ******************************************************************************/ // The Standard Template Library, or STL, is a C++ library of container classes, // algorithms, and iterators; // it provides many of the basic algorithms and data structures of computer science. // The STL is a generic library, meaning that its components are heavily parameterized: // almost every component in the STL is a template. #include <iostream> #include <vector> // Vectors are in the STL #include <stack> // Stacks are in the STL #include <string> // Strings are not in the STL, but many programmers consider them to be using namespace std; void main() { // A stack is last-in-first-out (LIFO) // We can use a stack object to model a shelf in the store. stack <string> cerealBoxes; // Cereal boxes on a shelf in the grocery store string strCerealBox; // Stock the shelf cerealBoxes.push("Captian Crunch"); cerealBoxes.push("Sugar Pops"); cerealBoxes.push("Special K"); cerealBoxes.push("Cheerios"); cerealBoxes.push("Coco Puffs"); cerealBoxes.push("Life"); // There's no method for determining how many elements are on the stack. Bummer. // A customer grabs the first box strCerealBox = cerealBoxes.top(); // Get the last cereal box that was pushed cerealBoxes.pop(); // Remove it from the virtual shelf cout << "\n The customer picked a box of " << strCerealBox.c_str(); cout << "\n\n"; }