手动实现Myvector。要实现的函数: 构造函数;析构函数;拷贝构造;拷贝赋值;at(); empty();full() ;front(); back(); size(); clear(); expand(); 二倍扩容函数
代码
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class Myvector
{
private:
T *first;
T *last;
T *end;
T data;
size_t size;
public:
Myvector():first(nullptr),last(nullptr),end(nullptr){}
Myvector(T n, T d):data(d), size(n)
{
first = new T(n);
last = first;
end = first+n;
for(int i=0; i<n; i++) {
*last = d;
last++;
}
}
void show() {
for(auto p=first; p!=last; p++) {
cout<<*p<<" ";
}
cout<<endl;
}
~Myvector(){
delete first;
first = nullptr;
delete last;
last = nullptr;
delete end;
end = nullptr;
}
Myvector(const Myvector &other):first(other.first), last(other.last), end(other.end), data(other.data),size(other.size){}
Myvector &operator=(const Myvector &other) {
this->first = other.first;
this->last = other.last;
this->end = other.end;
this->size = other.size;
return *this;
}
T &at(int n) {
T* p = first;
return *(p+n);
}
bool empty() {
return first == last;
}
bool full() {
return last==end;
}
T front() {
return *first;
}
T back() {
return *(last-1);
}
size_t T_size() {
return last-first;
}
void clear() {
first=last;
}
void expand() {
size_t size1 = T_size();
if(last==end) {
T *temp = new T[size1*2];
memcpy(first, temp, (sizeof(T)*size1));
delete []first;
first = temp;
last = first+size1;
end = first+(size1*2);
}
}
};
int main()
{
Myvector<int> v1(5,2);
v1.show();
Myvector<int> v2(v1);
v2.show();
cout<<"v2.at(2) = "<<v2.at(2)<<endl;
if(v1.empty()) {
cout<<"v1为空"<<endl;
}else {
cout<<"v1不为空"<<endl;
}
if(v2.full()) {
cout<<"v2为满"<<endl;
}else {
cout<<"v2不为满"<<endl;
}
cout<<"v2.T_size = "<<v2.T_size()<<endl;
return 0;
}
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/f6d29430a30b4c43bc35c07090f6dc76.png)