类模板实现简单的数组

发布时间 2024-01-13 21:15:52作者: λios
//Myarray.hpp
#pragma once

template<class T>

class MyArray {
public:
	MyArray(int capacity) {
		this->mCapacity = capacity;
		this->msize = 0;
		this->p = new T[this->mCapacity];
	}
	//copy
	MyArray(const MyArray& arr) {
		this->mCapacity = arr.mCapacity;
		this->msize = arr.msize;
		p = new T[arr.mCapacity];
		for (int i = 0; i < this->msize; ++i) p[i] = arr.p[i];
		
	}

	//operator =
	MyArray& operator=(const MyArray& arr){
		if (this->p != nullptr) {
			delete[] this->p;
			this->p = nullptr;
		}
		p = new T[arr.mCapacity];
		this->msize = arr.msize;
		this->mCapacity = arr.mCapacity;
		for (int i = 0; i < this->msize; ++i) p[i] = arr.p[i];
		return *this;
	}

	void push_back(const T& val) {
		if (this->msize == this->mCapacity) {
			T* np = new T[2 * this->mCapacity]{};
			this->mCapacity *= 2;
			for (int i = 0; i < this->msize; ++i) np[i] = this->p[i];
			delete[] this->p;
			this->p = nullptr;
			this->p = np;
		}
		this->p[this->msize] = val;
		++this->msize;
	}

	void pop_back() {
		if (this->msize == 0) return;
		this->p[msize] = {};
		--this->msize;
	}

	T operator[](int i) {
		return this->p[i];
	}

	~MyArray() {
		if (this->p != nullptr) {
			delete[] p;
			p = nullptr;
		}
	}

	int size() {
		return this->msize;
	}

private:
	T* p;
	int mCapacity;
	int msize;
};

这里是头文件

//main.cpp
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<numeric>
#include"Myarray.hpp"
using i64 = long long;

class Maker {
public:
	Maker() {}
	Maker(std::string name,int age){
		this->name = name;
		this->age = age;
	}
	std::string name;
	int age;
};

void printMaker(MyArray<Maker>& arr) {
	for (int i = 0; i < arr.size(); ++i) std::cout << arr[i].name << ' ' << arr[i].age << '\n';
}

void test() {
	MyArray<Maker> m(1);
	Maker m1("123", 200);
	Maker m2("321", 1200);
	Maker m3("456", 2100);
	Maker m4("654", 11200);
	m.push_back(m1);
	m.push_back(m2);
	m.push_back(m3);
	m.push_back(m4);
	printMaker(m);
}

auto main()->int32_t {

	std::cin.tie(nullptr)->sync_with_stdio(false);
	
	test();

	
	return static_cast<int32_t>(0);
}