动态数组C++实现方法(分享)

发布时间:2020-10-26 02:36:10 作者:jingxian
来源:脚本之家 阅读:134

回顾大二的数据结构知识。从数组开始。实现了一个可自动扩充容量的泛型数组。

头文件:Array.h

#ifndef Array_hpp
#define Array_hpp

template <class T>
class Array{
private:
  T *base;    //数组首地址
  int length;   //数组中元素
  int size;    //数组大小,以数组中元素的大小为单位
public:
  //初始化数组,分配内存
  bool init();
  //检查内存是否够用,不够用就增加
  bool ensureCapcity();
  //添加元素到数组尾
  bool add(T item);
  //插入元素到数组的具体位置,位置从1开始
  bool insert(int index,T item);
  //删除指定位置的元素并返回,位置从1开始
  T del(int index);
  //返回指定位置的元素
  T objectAt(int index);
  //打印数组所有元素
  void display();
};

#endif /* Array_hpp */

实现: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;
}

使用:

#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;
}

以上这篇动态数组C++实现方法(分享)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

推荐阅读:
  1. C++实现的动态数组
  2. Python实现动态数组的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

动态数组 c++

上一篇:android中关于call拨号功能的实现方法

下一篇:详解Angular 4 表单快速入门

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》