复制构造函数还没写,先这样吧,用编译器给的浅复制
#include <iostream>
#include <cstdio>
#include "memory.h"
struct type_false{
bool get(){
return false;
}
};
struct type_ture{
bool get(){
return true;
}
};
#define CASE(input) \
template <>\
struct input_type<input>{\
using _type_foo = struct type_ture;\
};
template <class T>
struct input_type{
using _type_foo = struct type_false;
};
CASE(char);
CASE(double);
CASE(long long);
CASE(float);
CASE(int);
CASE(unsigned int);
template <typename T>
class my_vector{
public:
my_vector(){
if(typename input_type<T>::_type_foo().get()){
_size = 0;
_capacity = 3;
head = (T *)malloc(_capacity * sizeof(T));
} else {
head = new T[3];
_size = 0;
_capacity = 3;
}
};
my_vector(const T& input){
if(typename input_type<T>::_type_foo().get()){
head = malloc(input._capacity * sizeof(T));
memcpy(head, input.head, input._size);
_size = input._size;
_capacity = input._capacity;
}
};
void push_back(T const input){
_chack_size();
this->head[_size] = input;
_size++;
}
void emplace_back(T &&input){
_chack_size();
this->head[_size++] = std::move(input);
}
~my_vector(){
if(typename input_type<T>::_type_foo().get()){
free(head);
}
else
delete[] head;
}
T& operator[](int const input){
if(input >= _size) {
std::cerr << "溢出" << std::endl;
exit(1);
}
return *(head + input);
}
size_t size(){
return _size;
}
void _chack_size(){
if(_size >= _capacity){
if(typename input_type<T>::_type_foo().get()){
T * temp = (T*) malloc((_capacity * 2) * sizeof(T));
memcpy(temp, head, _size * sizeof(T));
_capacity = _capacity * 2;
free(head);
head = temp;
}
else{
T *temp = new T[(_capacity * 2)];
for(int i = 0; i < _size; i++)
temp[i] = head[i];
_capacity = _capacity * 2;
delete[] head;
head = temp;
}
}
}
private:
T *head;
size_t _size;
size_t _capacity;
};
int main(){
//test1
my_vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
a.push_back(6);
a.push_back(7);
a.push_back(8);
a.push_back(9);
for(int i = 0; i < a.size(); i++)
std::cout << a[i] << std::endl;
test2
my_vector<int> q(a);
for(int i = 0; i < q.size(); i++)
std::cout << q[i] << std::endl;
}