#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first;
T * last;
T * end;
public:
Myvector():first(nullptr),last(nullptr),end(nullptr){cout<<"无参构造"<<endl;}
Myvector(T* f,T* e):first(f),last(f),end(e){cout<<"有参构造"<<endl;}
~Myvector(){cout<<"析构函数"<<endl;}
Myvector(const Myvector &other):first(other.first),last(other.last),end(other.end){
cout<<"拷贝构造"<<endl;
}
Myvector &operator=(const Myvector&other)
{
if(this != &other)
{
this->first = other.first;
this->last = other.last;
this->end = other.end;
}
}
void show()
{
for(T *temp = first;temp!=end;temp++)
{
cout<<* temp<<endl;
}
}
T at(int pos)
{
if(pos<0||pos>=*(end-first))
{
cout<<"请输入合法的位置"<<endl;
}
T* temp = first;
return *(temp+pos);
}
bool empty()
{
return first == last;
}
bool full()
{
return last == end;
}
T front()
{
cout<<*first<<endl;
return *first;
}
T back()
{
cout<<*last<<endl;
return *last;
}
int size()
{
return *(last)-*(first);
}
void clear()
{
delete []first;
first = last = end = nullptr;
}
T* expand()
{
T* temp = new T[2*(end-first)];
memcpy(temp,(void *)first,sizeof(T)*(end-first));
delete []first;
first = temp;
last = first + sizeof(temp)/2;
end = first + sizeof(temp);
return temp;
}
T* push_back(T data)
{
if(full())
{
expand();
last++;
*last = data;
}else {
last++;
*last = data;
}
return last;
}
T* pop_back()
{
if(last!=end)
{
delete last;
last--;
end--;
}else if (last == end) {
delete end;
last--;
end--;
}
return last;
}
};
int main()
{
Myvector<int>n1;
int* f = new int[10];
int* e = f+10;
Myvector<int>(f,e);
int num,value;
cout<<"请输入要输入的元素个数"<<endl;
cin>>num;
for(int i=0;i<num;i++)
{
cout<<"请输入元素的值"<<endl;
cin>>value;
n1.push_back(value);
}
cout<<"*********"<<endl;
n1.show();
n1.front();
n1.back();
cout<<"*********"<<endl;
cout<<n1.size()<<endl;
cout<<"请输入要输入的元素个数"<<endl;
cin>>num;
for(int i=0;i<num;i++)
{
cout<<"请输入元素的值"<<endl;
cin>>value;
n1.push_back(value);
}
cout<<"*********"<<endl;
n1.show();
n1.pop_back();
n1.show();
return 0;
}
C++ 作业 day 4
最新推荐文章于 2024-06-18 20:12:34 发布