Dynamic array C++ implements the method of sharing

  • 2020-05-19 05:25:09
  • OfStack

Review the data structure knowledge of big 2. We start with an array. An automatic expansion capacity of a generic array is implemented.

The header file: Array h


#ifndef Array_hpp
#define Array_hpp

template <class T>
class Array{
private:
  T *base;    // Array header 
  int length;   // Elements in an array 
  int size;    // The array size , In terms of the size of the elements in the array 
public:
  // Initialize the array and allocate memory 
  bool init();
  // Check if the memory is sufficient, and if not, increase it 
  bool ensureCapcity();
  // Add an element to the end of the array 
  bool add(T item);
  // Insert the element into the specific location of the array from 1 start 
  bool insert(int index,T item);
  // Deletes the element at the specified location and returns the location from 1 start 
  T del(int index);
  // Returns the element at the specified location 
  T objectAt(int index);
  // Prints all the elements of the array 
  void display();
};

#endif /* Array_hpp */

Implementation: Array cpp


#include "Array.hpp"
#include <mm_malloc.h>
#include <iostream>
using namespace std;

template<typename T> bool Array<T>::init(){  
  base = (T *)malloc(10*sizeof(T));
  if(!base){
    return false;
  }
  size = 10;
  length = 0;
  return true;
}

template<typename T> bool Array<T>::ensureCapcity(){
  if(length >= size){
    T *newBase = (T*)realloc(base,10 * sizeof(T) + size);
    if(!newBase){
      return false;
    }
    base = newBase;
    size += 10;
    newBase = nullptr;
  }
  return true;
}

template<typename T> bool Array<T>::add(T item){
  if(!ensureCapcity()){
    return false;
  }
  T *p = base + length;
  *p = item;
  length ++;
  return true;
}

template<typename T> bool Array<T>::insert(int index,const T item){
  if(!ensureCapcity()){
    return false;
  }
  if(index < 1 || index > length){
    return false;
  }
  T *q = base + index - 1;
  T *p = base + length - 1;
  while( p >= q){
    *(p+1) = *p;
    p--;
  }
  *q = item;
  q = nullptr;
  p = nullptr;
  length ++;
  return true;
}

template<typename T>T Array<T>::del(int index){
  if(index<1 || index > length){
    return NULL;
  }
  T *q = base + index - 1;
  T item = *q;
  ++q;
  T *p = base + length;
  while(q <= p){
    *(q-1)=*q;
    ++q;
  }
  length --;
  return item;
}

template<typename T>T Array<T>::objectAt(int index){
  if(index<1 || index > length){
    return NULL;
  }
  T *q = base;
  return *(q + index - 1);
}

template <typename T>void Array<T>::display(){
  T *q = base;
  T *p = base +length - 1;
  while (q<=p) {
    cout << *(q++)<<" ";
  }
  cout << endl;
}

Use:


#include <iostream>
#include "Array.cpp"
using namespace std;

int main(int argc, const char * argv[]) {
  Array<int> array = *new Array<int>;
  array.init();
  array.add(1);
  array.insert(1,2);
  array.objectAt(1);
  return 0;
}

Related articles: