1_c++实现简单vector

来源:互联网 发布:淘宝店铺主营在哪里改 编辑:程序博客网 时间:2024/06/05 00:13

实现了一些大概的功能,增加,删除,判空,修改,尾部插入,注释很详细,直接贴代码

头文件:CustomVector.h

#pragma oncetemplate<class T,int n>class CustomVector{private: T *p;//初始化数组p int cur_len;//记录现在有效长度的元素个数 int len;//记录总长度public:CustomVector<T,n>(void);~CustomVector<T,n>(void);void addNodeToLast(int val);void showVector();void deleNode(int pos);void insert(int pos,int value);void update(int pos,int value);bool isEmpty();};

类文件:CustomVector.cpp

#include "CustomVector.h"template<class T,int n>CustomVector<T,n>::CustomVector(void){this->p=new T[n];this->len=n;this->cur_len=len;for (int i=0;i<n;i++){*(p+i)=i;}}template<class T,int n>CustomVector<T,n>::~CustomVector(void){delete [] p;}template<class T,int n>void CustomVector<T,n>::addNodeToLast(int val){if (this->cur_len<this->len)//当数组长度还没有满的时候{*(p+(this->cur_len++))=val;}else{//重新申请一片内存,进行数组拷贝T *pt=p;p=new T[++this->len];for (int i=0;i<this->cur_len;i++){*(p+i)=*(pt+i);}p[this->cur_len]=val;this->cur_len++;}}template<class T,int n>void CustomVector<T,n>::showVector(){for (int i=0;i<this->cur_len;i++){printf("%d\t",*(p+i));}printf("\n");}template<class T,int n>void CustomVector<T,n>::deleNode(int pos){if (pos<0||pos>this->cur_len){return ;}//把后面的元素往前挪动一个单位,然后长度-1for (int i=pos-1;i<cur_len;i++){p[i]=p[i+1];}cur_len--;};template<class T,int n>void CustomVector<T,n>:: insert(int pos,int value){if (pos<0||pos>cur_len){return ;}//申请一片+1的内存if (cur_len>=len){T *pt=p;p=new T[++len];//拷贝数据for (int i=0;i<cur_len;i++){*(p+i)=*(pt+i);}}else{//往后挪动一个位置for (int i=cur_len-1;i>=pos-1;i--){p[i+1]=p[i];//把pos-1之后的元素都往后挪动一个单位}p[pos-1]=value;cur_len++;//插入成功后+1}}template<class T,int n>bool CustomVector<T,n>:: isEmpty(){if (cur_len==0){return false;}else{return true;}}template<class T,int n>void CustomVector<T,n>::update(int pos,int value){if (pos<0||pos>len){return ;}p[pos-1]=value;}

简单测试文件:main.cpp

#include <stdlib.h>#include <stdio.h>using namespace std;#include "CustomVector.h"#include "CustomVector.cpp"void main(){CustomVector<int ,10> vctor;printf("初始化数据:\n");vctor.showVector();vctor.addNodeToLast(5);printf("插入一个节点:\n");vctor.showVector();printf("删除两个节点:\n");vctor.deleNode(0);vctor.deleNode(1);vctor.showVector();printf("插入一个节点\n");vctor.insert(5,3);vctor.showVector();printf("修改一个节点\n");vctor.update(5,4);vctor.showVector();system("pause");}


输出:

初始化数据:
0       1       2       3       4       5       6       7       8       9


插入一个节点:
0       1       2       3       4       5       6       7       8       9
5
删除两个节点:
2       3       4       5       6       7       8       9       5
插入一个节点
2       3       4       5       3       6       7       8       9       5

修改一个节点
2       3       4       5       4       6       7       8       9       5


Press any key to continue . . .


原创粉丝点击