通过类模板,实现一个简单的vector容器,实现vector类的无参构造、有参构造、拷贝构造、重载等号操作符、尾插、尾删、获取大小、获取容量、随机访问。
#include<iostream>
template <typename T>
class Vector {
private:
T* data;
int size;
int capacity;
public:
//无参构造
Vector() {
this->size = 0;
int newcapacity = 10;
this->capacity = newcapacity;
data = new T[capacity];
}
//有参构造
Vector(int newsize, T element) {
this->capacity = newsize * 2;
data = new T[capacity];
this->size = newsize;
for (int i = 0; i < this->size; i++) {
data[i] = element;
}
}
//拷贝构造
Vector(const Vector& p) {
this->size = p.size;
this->capacity = p.capacity;
this->data = new T[p.capacity];
for (int i = 0; i < this->size; i++) {
this->data[i] = p.data[i];
}
}
//重载等号运算符
T& operator= (const Vector& p) {
//检查原本容器是否分配了内存空间
if (this->data != nullptr) {
delete[] this->data;
this->data = nullptr;
this->capacity = 0;
this->size = 0;
}
//进行深拷贝
this->capacity = p.capacity;
this->size = p.size;
this->data = new T[this->capacity];
for (int i = 0; i < this->size; i++) {
this->data[i] = p.data[i];
}
return *this;
}
//析构
~Vector() {
if (this->data != nullptr) {
delete[] data;
this->data = nullptr;
}
}
//尾插
void push_back(T element) {
if (this->size == this->capacity) {
this->capacity = this->capacity * 2;
T* new_data = new T[this->capacity];
for (int i = 0; i < this->size; i++) {
new_data[i] = this->data[i];
}
delete[] data;
this->data = new_data;
}
this->data[this->size ++] = element;
};
//尾删
void pop_back() {
if (this->size == 0) {
std::cout << "删除失败" << std::endl;
return;
}
this->size--;
}
int get_size() {
return this->size;
}
int get_capacity() {
return this->capacity;
}
T& operator[](int index) {
if (index < 0 || index > this->size) {
throw std::out_of_range("index out of range");
}
return this->data[index];
}
};