手撕vector(简易版)

通过类模板,实现一个简单的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];
	}
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值