C ++: simple stack implementation using sequence tables
Main. cpp # include <iostream> # include <string> # include "Stack. hpp "using namespace std; void test1 () {// test Stack <int> s1; s1.Push (1); s1.Push (2); s1.Push (3); s1.Push (4 ); s1.Pop (); s1.Pop (); s1.Pop (); s1.Pop ();} int main () {test1 (); return 0;} Stack. hpp # pragma oncetemplate <class T> // you can use a template to implement multiple types of Stack operations class Stack {private: T * _ array; // data structure size_t _ capacity; // number of incoming stacks int _ topindex; // empty Stack/full judgment standard public: Stack (): _ array (0), _ capacity (0 ), _ topindex (-1) {} void Push (const T & x) {// inbound stack if (_ topindex + 1 = _ capacity) {// determine whether to open up space _ capacity = 2 * _ capacity + 3; T * tmp = new T (_ capacity); if (tmp = NULL) {cout <"failed new" <endl; exit (-1);} memcpy (tmp, _ array, sizeof (T) * (_ topindex + 1 )); // use delete _ array for built-in types; // memcpy, custom _ array = tmp; // use the for loop to copy one by one} // note the deep copy and pre-copy _ array [++ _ topindex] = x;} void Pop () {// out-of-stack if (_ topindex>-1) {cout <_ array [_ topindex] <endl; _ topindex -- ;}} bool empty () {// clear stack return _ topindex =-1 ;}};