Data structure (04) _ Implementation of an array class

Source: Internet
Author: User
Tags array length

Native arrays are supported in C + +, but due to natural flaws in native arrays (cannot get length information, cross-border access will not error ...) , we need to develop our own array classes to solve these problems.
Inheritance relationships for array classes

19. Implementation of the array class _119.1. Abstract class Template Array

Requirements Analysis:
1, because of the linear table, cannot be used as an array directly, we need to implement an array class to replace the original array.
2, solve the problem of the original array cross-border access will not give an error
3, provide the length of the array information

19.2.Array Design Highlights:
    • Abstract class modeled, the location and size of the storage space are specified by the subclass.
    • Overload array operators and determine if access subscript is out of bounds (legal)
    • Abstract access function that provides array length information
    • Provides copy operations between array objects (done by overloading copy constructors and assignment operators)
      template < typename T >class Array : public Object{protected:T *m_array;public:T& operator [] (int index)T operator [] (int index) constbool get(int index, const T& e)bool set(int index, const T& e)virtual int length(void) = 0;};
      19.2.1. Array implementation
#ifndef arrry_h#define arrry_h#include "Object.h" #include "Exception.h" namespace Dtlib{template < typename T > Class Array:public Object{protected:t *m_array;public:t& operator [] (int index) {if (index>=        0) && (index<length ())) {return m_array[index];        } else {throw_exception (indexoutofboundsexception, "array index out of range ...");    }} T operator [] (int index) const {return const_cast<array<t>&> (*this) [index];        } bool Get (int index, const t& e) {BOOL ret = (index>=0) && (Index<length ());        if (ret) {e = M_array[index];    } return ret;        } bool Set (int index, const t& e) {BOOL ret = (index>=0) && (index<length);        if (ret) {M_array[index] = e;    } return ret; } virtual int length (void) = 0;};} #endif//ARRry_h 
Implementation of the 19.3.StaticArray

Design Essentials:

    • encapsulates the native array;
    • Using template parameters to determine the size of an array
    • Implement function return array length
    • Copy Construction and assignment overloading
      template < typename T, int N >class StaticArray : public Array<T>   protected:T m_space[N];public:StaticArray()// 提供拷贝构造喊赋值重载函数,实现数组的拷贝StaticArray(const StaticArray<T, N>& obj)T& operator = (const StaticArray<T, N>& obj)int length(void)};
      19.3.1. Implementation of Staticarray
#ifndef STATICARRAY_H#define STATICARRAY_H#include "Array.h"namespace DTLib{template <typename T, int N>class StaticArray : public Array<T>{protected:    T m_space[N];public:    StaticArray()    {        this->m_array = m_space;    }    StaticArray(const StaticArray<T, N>& obj)    {        this->m_array = m_space;        for(int i=0; i<length();i++)   // 数组元素拷贝        {            m_space[i] = obj.m_space[i];        }    }    T& operator ==(const StaticArray<T, N>& obj)    {        if(this != &obj)        {            this->m_array = m_space;            for(int i=0; i<length();i++)            {                m_space[i] = obj.m_space[i];            }        }    }    int length(void)    {        return N;    }};}#endif // STATICARRAY_H
20. Realization of the implementation _220.1.dynamicarray of the array class

Design Essentials: Class templates

    • dynamically determines the size of the internal array space
    • implementation function returns the length of the array
    • copy construction and assignment operation
        template < typename T >class Dynamicarr Ay:public array<t>{protected:int m_length;public:dynamicarray (int length) Dynamicarray (const DynamicArray< t>& obj) dynamicarray<t>& operator = (const dynamicarray<t>& obj) void resize (int length) ~ Dynamicarray ()};  
      20.2.DynamicArray code Optimization

      The function implementations in the Dynamicarray class have repetitive logic that can be optimized for code.
      The abstraction of repeating code logic:
      The initialization of the-init function when the object is constructed
      The-copy function is responsible for requesting memory from the heap space and performing a copy construction operation
      -updata using the specified heap space as an internal storage array

      20.2.1. Dynamicarray implementation
#ifndef dynamiclist_h#define dynamiclist_h#include "SeqList.h" namespace Dtlib{template <typename T>class Dynamiclist:public seqlist<t>{protected:int m_capacity;public:dynamiclist (int capacity) {this-&        Gt;m_array = new T[capacity];            if (this->m_array! = NULL) {this->m_length = 0;        This->m_capacity = capacity;        } else {throw_exception (noenoughmemoryexception, "No memory to create Dynamiclist object ...");    }} int capacity () const {return m_capacity;            } void resize (int capacity) {if (capacity! = m_capacity) {t* array = new t[capacity]; if (array! = NULL) {int length = (This->m_length < capacity? This->m_length:                capacity);                for (int i=0;i<length;i++) {Array[i] = this->m_array[i]; } t* temp = This-> M_array;                This->m_array = array;                this->m_length = length;                This->m_capacity = capacity;            Delete[] temp; } else {throw_exception (noenoughmemoryexception, "No memory to create Dynamiclist obj            ECT ... ");    }}} ~dynamiclist () {delete[] this->m_array; }};} #endif//Dynamiclist_h

Summarize:

    • Staticarray implements array classes by encapsulating native arrays
    • Dynamicarray Dynamic Application heap space, making the array length dynamic variable
    • Array objects can replace native arrays and use more secure
    • Project development is an essential part of code optimization

Data structure (04) _ Implementation of an array class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.