C ++ actual combat: realization of a light array class

xiaoxiao2021-03-06  95

C actual combat: realization of a light array class

Description: This array class can be considered as a simplified version of the vector library: supporting the general operation of array, supporting copy, assignment, supporting the redefine size; do not consider multithreading, regardless of pre-allocation extra space, performance optimization, no Set an iterator.

#include // is only used for testing, and the array class itself does not need

Template class array {public: type (//) size (subscript) type of type_tp; // array

Array (size tty = type ()); // You can specify the initial size with size, T specify the initial value array (const array & array); ~ array (); // space is automatically released

TYPE & OPERATOR [] (SIZE_TP INDEX); // Upload Access (Read / Write Form) Const Type & Operator [] (SIZE_TP INDEX) Const; / / Subscriber Access (read-only) Array & Operator = (Const Array & RHS); // Assignment, change the size / content

SIZE_TP GET_SIZE () const; // Get array size void resize (size_tp size); // Reset an array size, if you change, drop the tail data

Void Push_Back (const type & value); // Add an array element, an array size increases

PRIVATE: VOID COPY (const type * p_source, type * p_target, size_tp size); size_tp _size; type * _arr;};

Template :: array (size_tp size, type t): _size (size), _ARR (size? new type [size]: 0) {for (size_tp i = 0; i

Template :: array : _ size (array._size), _ arr (array._size? new type [array._size]: 0) {copy (_Array._arr, _arr, Array._size); // do nothing if (array._size == 0)}

Template Array :: ~ array () {delete [] _arr;}

Template & array :: operator = (const array & rhs) {if (& rhs! = this) {resize (rhs._size); Copy (rhs._arr, _arr , _Size);} return * this;} template :: operator []_ = _size) THROW ("Array :: out of range"); Return _arr [index];

Template Const Type & Array :: Operator [] ("Array :: Out of Range"); Return_arr [index]; Return_Arr [index];

Template :: size_tp array :: get_size () const {return_size;

Template :: copy (const type * p_source, type_tp size) {for (size_tp i = 0; i

Template :: resize (size_tp new_size) {if (new_size) {type * p = new type [new_size]; copy (_arr, p, _size

Template Void Array :: Push_Back (const type & value) {resize (_size 1); _arr [_size - 1] = value;}

INT Main () // Main Test Function {Array A (30, 5); Array B; B.Push_Back (20); B.PUSH_BACK (100); A = B; for (Array :: size_tp i = 0; i

转载请注明原文地址:https://www.9cbs.com/read-123870.html

New Post(0)