65.9K
CodeProject is changing. Read more.
Home

A light stack implementation for Win32

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.11/5 (6 votes)

Mar 19, 2004

viewsIcon

52881

downloadIcon

322

A simple and very small stack implementation for any type.

Introduction

This is a small stack implementation that is relied on MFC CArray template class. It has implemented the three mostly needed stack functions Push, Pop and Peek. The class is directly derived from CArray and consequently it supplies all inherited functions too.

Usage sample

CStack<int> m_stack;
m_stack.Push( 1973 );
m_stack.Push( 2004 );
m_stack.Push( 30 ); 
int size = m_stack.GetSize();// an inherited CArray function. 

int value = m_stack.Peek(); // only returns the last inserted value 

int value = m_stack.Pop(); // returns the last inserted value

                          // and removes it from stack.

The implementation

// Copyright (C) 2003 by Daniel Junges 

// http://junges.gmxhome.de/

// Written by Daniel Junges daniel-junges@gmx.net

// All rights reserved

//

// This is free software.

// This code may be used in compiled form in any way you desire. :-)

//

// Release Date and Version:

// Version: 1.0 Mars 2003

//////////////////////////////////////////////////////////////////////

// 


#ifndef _H_TEMPLATE_H_
#define _H_TEMPLATE_H_


template <class T> class CStack : public CArray<T,T>
{
public:
 // Add element to top of stack

 void Push( T newView ){ 
  Add( newView );
 }
 // Peek at top element of stack

 T Peek(int index=-1){ 
  return ( index >= GetSize() || 
    GetSize()==0) ? NULL : ElementAt( ( index==-1?GetSize()-1:index) ); 
 }
 // Pop top element off stack

 T Pop(){ 
  T item = Peek();
  if(item) RemoveAt(GetSize()-1);
  return item; 
 }
};


#endif