[转]C++实现动态数组
来源:互联网 发布:fittime软件好用吗. 编辑:程序博客网 时间:2024/05/22 22: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;}
阅读全文
0 0
- C实现动态数组
- 动态数组C语言实现
- C语言实现动态数组
- 动态数组的 C 实现
- C/C++实现动态数组
- C语言实现动态数组
- c语言实现动态数组
- 链表实现动态数组C源代码
- C/C++语言实现动态数组
- C/C++语言实现动态数组
- C语言动态数组的完整实现
- C语言实现 vector( 动态数组)。
- C语言堆栈实现( 动态数组 )
- C语言队列实现( 动态数组 )
- C语言实现 vector( 动态数组)
- C语言动态数组的完整实现
- C语言 -----动态数组算法实现
- C语言中动态数组的实现
- Android如何做到应用程序图标隐藏,由第三方程序启动
- MeasureSpec笔记
- Ubuntu 14.04 安装 Sublime Text 3
- android activity 生命周期及启动模式
- 【计算机视觉】结构光——格雷码模式捕获教程2(经典论文)
- [转]C++实现动态数组
- OsmocomBB 代码分析(1)
- 使用Systrace分析UI性能
- 程序性动画 2 ——正向运动学的数学运算
- 队列的存储结构,判空、插入、删除操作
- applicationContext.xml的基本配置文件
- 通过服务器日志溯源web应用攻击路径
- iOS开发-- 字符串分割(多个字符分割一个字符串)、拼接
- error LNK2026: 模块对于 SAFESEH 映像是不安全的-VS2013