|
发表于 2020-8-8 17:51:55
|
显示全部楼层
本楼为最佳答案
试了下,可以正常编译执行,下面是完整代码,三个文件,其中有几个小修改,
你复制完整代码看正常不。我是在VS2015下运行的。
//Vector.h
- #ifndef VECTOR_H_
- #define VECTOR_H_
- #define SUCCESS 1 // 成功
- #define ERROR -1 // 失败
- #define MALLOC_ERROR -2 // 申请内存失败
- #define INDEX_ERROR -3 // 错误的索引号
- template<class T_ELE>
- class Vector
- {
- private:
- T_ELE *pVector;
- int Len;
- int Index;
- int InitSize;
- int Increment;
- public:
- Vector<T_ELE>();
- Vector<T_ELE>(int size);
- ~Vector<T_ELE>();
- int push_back(T_ELE Element);
- bool expand();
- int insert(int index, T_ELE Element);
- };
- #endif
复制代码
//Vector.cpp
- #include "Vector.h"
- template<class T_ELE>
- Vector<T_ELE>::Vector() : InitSize(100), Increment(5)
- {
- //分配空间
- //pVector = new T_ELE(InitSize);
- pVector = new T_ELE[InitSize];
- //初始化
- memset(pVector, 0, InitSize * sizeof(T_ELE));
- //其他变量初始化
- Len = InitSize;
- Index = 0;
- }
- template<class T_ELE>
- Vector<T_ELE>::Vector(int size) : Increment(5) //增加了Increment(5)
- {
- //分配空间
- //pVector = new T_ELE(size);
- pVector = new T_ELE[size];
- //初始化
- memset(pVector, 0, size * sizeof(T_ELE));
- //其他变量初始化
- Len = size;
- Index = 0;
- }
- template<class T_ELE>
- Vector<T_ELE>::~Vector()
- {
- //释放类对象里面申请的空间
- delete[]pVector;
- pVector = NULL;
- }
- template<class T_ELE>
- int Vector<T_ELE>::push_back(T_ELE Element)
- {
- //判断是否需要增容
- if (Index >= Len)
- {
- expand();
- }
- //将新元素放到最后一个位置
- memcpy(&pVector[Index], &Element, sizeof(T_ELE));
- //修改索引
- Index++;
- //返回成功
- return SUCCESS;
- }
- //扩容
- template<class T_ELE>
- bool Vector<T_ELE>::expand()
- {
- int tlen;
- int* pNew;
- //计算增加后的长度
- tlen = Len + Increment;
- //申请现在需要的空间
- //pNew = new T_ELE(tlen);
- pNew = new T_ELE[tlen];
- //将数据复制到新空间
- memcpy(pNew, pVector, Len*sizeof(T_ELE));
- //释放原来的空间
- delete[]pVector;
- pVector = pNew;
- pNew = NULL;
- //修改其他变量值
- Len = tlen;
- return SUCCESS;
- }
- //插入数据
- template<class T_ELE>
- int Vector<T_ELE>::insert(int index, T_ELE Element)
- {
- //判断索引是否在合理区间
- if (index<0 || index>Index)
- return INDEX_ERROR;
- //判断是否需要扩容
- if (Index >= Len)
- expand();
- //将索引后面的元素全部后移
- for (int i = Index; i>index - 1; i--)
- memcpy(&pVector[i], &pVector[i - 1], sizeof(T_ELE));
- //将元素插入对应的位置
- memcpy(&pVector[index - 1], &Element, sizeof(T_ELE));
- //修改其他对应的参数
- Index++;
- }
复制代码
//test.cpp
- #include<iostream>
- #include <string.h>
- #include "Vector.h"
- #include "Vector.cpp"
- using namespace std;
- //测试函数
- void TextVector()
- {
- Vector<int>* p = new Vector<int>(5);
- p->push_back(1);
- p->push_back(2);
- p->push_back(3);
- p->push_back(4);
- p->push_back(5);
- p->push_back(6);
- }
- int main()
- {
- TextVector();
- return 0;
- }
复制代码 |
|