MyArray.hpp
//
// Created by Cauchyshy on 2023/4/27.
//
#ifndef STU_IPR_MYARRAY_HPP
#define STU_IPR_MYARRAY_HPP
#endif //STU_IPR_MYARRAY_HPP
// 手撕简洁版vector
#pragma once
#include <iostream>
#include <String>
using namespace std;
template<typename T>
class Vector {
private:
T *pAddress; // 指针指向堆区开辟的真实数组
int Capacity; // 数组容量
int Size; // 数组大小
public:
// 有参构造 参数 容量
Vector(int capacity) {
// cout << "Vector的有参构造函数" << endl;
this->Capacity = capacity;
this->Size = 0;
this->pAddress = new T[this->Capacity];
}
// 拷贝构造
Vector(const Vector &vec) {
// cout << "Vector的拷贝构造函数" << endl;
this->Size = vec.Size;
this->Capacity = vec.Capacity;
// 深拷贝
this->pAddress = new T[vec.Capacity];
// 将vec中的数据拷贝过来
for (int i = 0; i < vec.Size; ++i) {
this->pAddress[i] = vec.pAddress[i];
}
}
// 重载= 防止浅拷贝问题 a = b = c
Vector& operator = (const Vector &vec) {
// cout << "重载了Vector的=" << endl;
// 先判断原来堆区数据是否为空 若有先释放
if (this->pAddress != NULL) {
delete[] this->pAddress;
this->pAddress = NULL;
this->Capacity = 0;
this->Size = 0;
}
// 深拷贝
this->Capacity = vec.Capacity;
this->Size = vec.Size;
this->pAddress = new T[vec.Capacity];
for (int i = 0; i < vec.Size; ++i) {
this->pAddress[i] = vec.pAddress[i];
}
return *this;
}
// 尾插法
void push_Back(const T &val) {
// 判断有没有超过容量
if (this->Capacity == this->Size) {
cout << "塞满了插不进去嘞!" << endl;
return ;
}
// 因为下标是从0 开始的 所以尾插要插的位置就是this->Size
this->pAddress[this->Size] = val;
this->Size++;
}
// 尾删法
void pop_Back() {
// 让用户访问不到最后一个元素即可 逻辑删除
if (this->Size == 0) {
cout << "都没有元素你咋删啊?" << endl;
return ;
}
this->Size--;
}
// 通过下标访问数组元素 比如vec[2] 重载[]即可 返回引用就可作为左值存在了
T& operator [] (int index) {
return this->pAddress[index];
}
// 返回数组容量
int getCapacity() {
return this->Capacity;
}
// 返回数组大小
int getSize() {
return this->Size;
}
// 析构函数
~Vector() {
if (this->pAddress != NULL) {
// cout << "Vector的析构函数" << endl;
delete[] this->pAddress;
this->pAddress = NULL;
}
}
};
测试代码
//
// Created by Cauchyshy on 2023/4/27.
//
#include <iostream>
#include "MyArray.hpp"
using namespace std;
class Person {
public:
string name;
int age;
Person() {};
Person(string name, int age) {
this->name = name;
this->age = age;
}
};
void test() {
Vector<int> vec(5);
cout << "vec的容量为: " << vec.getCapacity() << endl;
for (int i = 0; i < 5; ++i) {
vec.push_Back(i + 1);
}
for (int i = 0; i < vec.getSize(); ++i) {
cout << vec[i] << " \n"[i == 4];
}
int t = vec.getSize();
for (int i = 0; i < t; ++i) vec.pop_Back();
cout << "删除后的大小为" << vec.getSize() << endl;
Vector<Person> vec2(10);
Person p1("xmu1", 18);
Person p2("xmu2", 19);
Person p3("xmu3", 20);
Person p4("xmu4", 21);
Person p5("xmu5", 22);
vec2.push_Back(p1);
vec2.push_Back(p2);
vec2.push_Back(p3);
vec2.push_Back(p4);
vec2.push_Back(p5);
cout << "vec2的容量为: " << vec2.getCapacity() << endl;
for (int i = 0; i < vec2.getSize(); ++i) {
cout << "name->" << vec2[i].name << " age->" << vec2[i].age << endl;
}
vec2.pop_Back();
cout << "删除一个元素后的大小为" << vec2.getSize() << endl; // 4
}
int main() {
test();
return 0;
}