手动实现My_vector
template <typename T>
class Myvector { private: T * first; T * last; T * end; };
要实现的函数: 构造函数 析构函数 拷贝构造 拷贝赋值 at() empty() full() front() back() size() clear() expand() 二倍扩容函数 push_back() pop_back()
main.cpp:
#include <iostream>
//#include <header.h>
using namespace std;
template<typename T>
class Myvector
{
public:
T *first; //指向第一个元素的位置
T *last; //指向最后一个元素的后一个位置
T *end; //指向最大容量的后一个位置
public:
Myvector() //无参构造
{
cout << "无参构造" << endl;
first = new T[1];
end = first;
last = first;
}
Myvector(int num, const T &val) //有参构造
{
cout << "有参构造" << endl;
last = first = end = new T[num];
for(int i = 0; i < num; i++)
{
*last = val;
last++;
}
end += num;
}
~Myvector() //析构函数
{
cout << "析构函数" << endl;
delete []first;
end = last = first = nullptr;
}
Myvector(const Myvector<T> &other):first(new T(*(other.first))), last(new T(*(other.last))), end(new T(*(other.end))) //拷贝构造
{
cout << "拷贝构造函数" << endl;
}
Myvector<T> & operator=(const Myvector<T> &other) //拷贝赋值
{
cout << "拷贝赋值函数" << endl;
int size = other.end-other.first;
int len = other.last-other.first;
delete []first;
first = new T[size];
for(int i=0;i<len;i++)
{
first[i]=other.first[i];
last++;
}
end = first + size;
return *this;
}
bool empty() //判空函数
{
return first == last;
}
bool full() //判满函数
{
return last == end;
}
T &at(int index) //返回指定位置的元素
{
if(index < 0 || index >= (end-first))
cout << "数组越界" << endl;
return *(first+index-1);
}
int size() //返回元素数量的大小
{
return last-first;
}
T front() //返回第一个元素
{
//判断逻辑
if(empty()==true)
cout << "Myvector中无元素" << endl;
return *first;
}
T back() //返回最后一个元素
{
return *last;
}
void push_back(const T &val) //在最后添加一个元素
{
if(end==first)
end = first+1;
if(full()==true)
//二倍扩容
expand();
*(last++)=val;
}
void pop_back() //移除最后一个元素
{
//判空
if(empty()==true)
cout << "数组已空" << endl;
cout << *(last-1) << "已移除" << endl;
last--;
}
void clear() //清空所以元素
{
while(first!=last)
pop_back();
}
void expand() //二倍扩容
{
int len = size();
T *temp = new T[len];
memcpy(temp, first, sizeof(T)*len);
delete []first;
first = temp;
last = first+len;
end = first+2*len;
}
void show()
{
cout << "此时Myvector中元素有:";
for(int i = 0; i < (last-first); i++)
cout << *(first+i) << " ";
cout << endl;
}
};
int main()
{
Myvector<int> v1(3,3);
cout << "v1.size = " << v1.size() << endl;
cout << "v1.capacity = " << v1.end-v1.first << endl;
v1.show();
v1.push_back(1);
cout << "v1.size = " << v1.size() << endl;
cout << "v1.capacity = " << v1.end-v1.first << endl;
v1.show();
Myvector<int> v2;
v2 = v1;
cout << "v2.size = " << v2.size() << endl;
cout << "v2.capacity = " << v2.end-v2.first << endl;
v2.push_back(1);
cout << "v2.size = " << v2.size() << endl;
cout << "v2.capacity = " << v2.end-v2.first << endl;
v2.show();
return 0;
}
测试结果如下: