国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

動態數組C++實現方法(分享)

2020-01-26 14:07:37
字體:
來源:轉載
供稿:網友

回顧大二的數據結構知識。從數組開始。實現了一個可自動擴充容量的泛型數組。

頭文件:Array.h

#ifndef Array_hpp#define Array_hpptemplate <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++實現方法(分享)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 庄河市| 保定市| 无锡市| 自贡市| 霍林郭勒市| 曲靖市| 韶山市| 昌邑市| 赤水市| 伊宁市| 微山县| 合水县| 仁寿县| 苍梧县| 桂东县| 镇雄县| 新乐市| 隆尧县| 江山市| 萨迦县| 海南省| 沭阳县| 曲麻莱县| 临猗县| 留坝县| 襄城县| 泽库县| 台北市| 金阳县| 洛阳市| 江城| 突泉县| 安达市| 江西省| 仙居县| 资源县| 红原县| 盘山县| 蓝山县| 平顶山市| 清镇市|