|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 爱学习520 于 2020-8-10 09:12 编辑
昨天写到现在,实现Vector的底层实现,代码相对而言比较简单,应该都可以看懂,我把注释写的很清楚,结构也很明确
Vector类的实现:
- #include<iostream>
- #include<string.h>
- #define SUCCESS 1 //成功
- #define INDEX_ERROR -1 // 错误的索引号
- using namespace std;
- //定义Vector类
- template<class T_ELE>
- class Vector
- {
- private:
- int InitSize;
- int Len;
- int Index;
- int Increment;
- T_ELE* pVector;
- private:
- bool expand()
- {
- int tlen;
- T_ELE* pNew;
- //计算扩容后的长度
- tlen = Len + Increment;
- //重新申请适应新的需要的空间大小
- pNew = new T_ELE[tlen];
- //将原来的空间的数据复制到新申请的空间
- memcpy(pNew, pVector, Len * sizeof(T_ELE));
- //释放原先的空间
- delete[] pVector;
- pVector = pNew;
- //修改其他对应的值
- Len = tlen;
- return SUCCESS;
- }
- public:
- Vector():InitSize(10),Increment(5)
- {
- //分配空间
- pVector = new T_ELE[InitSize];
- //初始化申请的空间
- memset(pVector, 0, InitSize * sizeof(T_ELE));
- //初始化其他变量
- Len = InitSize;
- Index = 0;
- }
- Vector(int size) :Increment(5)
- {
- //分配空间
- pVector = new T_ELE[size];
- //初始化
- memset(pVector, 0, size * sizeof(T_ELE));
- //其他变量初始化
- Len = size;
- Index = 0;
- }
- ~Vector()
- {
- //释放申请的堆空间
- delete[] pVector;
- pVector = nullptr;
- }
- public:
- void push_back(T_ELE Element)
- {
- //判断是否需要增容
- if (Index >= Len)
- expand();
- //将新的元素放到最后一个位置
- pVector[Index] = Element;
- //修改对应的变化值
- Index++;
- }
-
- int insert(int index, T_ELE Element)
- {
- //检测插入的区间是否有误
- if (index < 1 || index > Index + 1)
- {
- cout << index<<"不在区域范围,插入错误!" << endl;
- return INDEX_ERROR;
- }
- //判断是否需要扩容
- if (Index >= Len)
- expand();
- //插入位置的元素和插入元素之后的所有元素后移
- memcpy(&pVector[index], &pVector[index - 1], (Index - index+1 ) * sizeof(T_ELE));
- pVector[index - 1] = Element;
- //对应的其他成员值的变化
- Index++;
- return 0;
- }
- int at(int index)
- {
- //判断索引是否在合理区间
- if (index<1 || index>Index)
- {
- cout<<index << "不在区域内,查找越界" << endl;
- return INDEX_ERROR;
- }
- //返回该索引对应的值
- return pVector[index - 1];
- }
- };
复制代码
测试案例:
- #include "Vector.cpp"
- //测试函数
- int main()
- {
- Vector<int> s(5);
- s.push_back(1);
- s.push_back(2);
- s.push_back(3);
- s.push_back(4);
- s.push_back(5);
- //测试增容
- s.push_back(6);
- //测试插入的临界错误区域
- s.insert(0,520);
- s.insert(8,520);
- //测试插入的临界正确区域
- s.insert(1,520);
- s.insert(3,520);
- s.insert(7,520);
- //显示经上述测试后目前Vector里面的元素,以判断是否正确,或者通过调试查看
- for (int i = 0; i < 9; i++)
- cout << s.pVector[i] << endl;
- //最后测试at函数
- s.at(0);
- s.at(4);
- s.at(9);
- s.at(10);
-
- return 0;
- }
复制代码 |
|