// With a template class to implement a dynamic array. #include "stdafx.h" #include "string.h" #include
Template Class List {private: t * data; size_t size; size_t capacity; public: list (); ~ list (); list (const list & ls); int push_back (t); t pop_head (); t & operator [] (SIZE_T INDEX); List & Operator = (Const List & LS); BOOL OPERATOR == (Const T1);};
Template List :: List () {size = 0; Capacity = 1; DATA = New T [SIZEOF (T)]; // Establish type means, can put down a type is enough.
Template List :: List (const list & rl) {data = new t [rl.capacity * sizeof (t)]; Memcpy (data, rl.data, rl.capacity * sizeof T)); size = rl.size; capacity = rl.capacity;
Template List :: ~ List () {delete [] data;}
Template List & List :: Operator = (Const List & RS) {if (this! = & = & = r) // Contrast Address {Delete []-> data; data = new T [SIZEOF (T) * rs.capacity]; // Type size multiplied by capacity size = rs.size; capacity = rs.capacity; memcpy (data, rs.data, sizeof (t) * rs.capacity;} return * this;}
Template T & List :: Operator []_t index) {if (index <0 || index> size) throw "range overflows!"; else return data;}
Template int List :: Push_Back (t t) {
INT DETA = 0; if (Capacity == Size) // Early application, algorithm optimization {if (Capacity> 64) Deta = Capacity / 4; Else IF (Capacity> 8) Deta = 8; Else Deta = 4; Capacity = DETA; T * TEMP = New T [size * sizeof (t)]; Memcpy (TEMP, DATA, SIZE * SIZEOF (T)); // Save the original value into the temporary variable
Delete [] data; data = new T [Capacity * sizeof (t)]; Memcpy (Data, Temp, Size * SizeOf (T)); // Restore the original data delete [] Temp;}}}} {DATA [size] = T; size; return size;} else return 0;
INT Main (int Argc, char * argv []) {list L1; char * a = "aaaa"; l1.push_back (a); a = "bbbb"; l1.push_back (a); a = "cccc"; l1.push_back (a); try {printf ("f1 =% S / N", L1 [2]);} catch (char * a) {printf ("throw =% s / n", A }
List ilist; ilist.push_back (10); ilist.push_back (20); ilist.push_back (30); int K = ilist [2]; Printf ("k =% D", K);
Return 0;}