ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

CPP STL Intro - The Stack

Updated on May 2, 2010


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:                                   *
 * Other resources:          *
 * Chapter 22 from our book: *
 * The book:           *

//  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("Coco Puffs");
//    There's no method for determining how many elements are on the stack. Bummer.

//    A customer grabs the first box
    strCerealBox =;    // 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";


    0 of 8192 characters used
    Post Comment

    No comments yet.