2.7作业

template<typename T>

class Myvector

{

private:

T* first;

T* last;

T* end;

public:

Myvector(){};

Myvector(int num,T e);

Myvector(const Myvector& from);

~Myvector();

Myvector& operator=(const Myvector& from);

T& at(int loc);

T& front();

T& back();

bool empty();

bool full();

int size();

void clear();

T* expand();

void push_back(T e);

void pop_back();

};

template<typename T>

Myvector<T>::Myvector(int num,T e)

{

first=new T[num];

last=first;

end=first+num;

for(int i=0;i<num;i++)

{

*(first+i)=e;

last++;

}

}

template<typename T>

Myvector<T>::Myvector(const Myvector<T>& from)

{

int num=from.end-from.first;

first=new T[num];

last=first;

end=first+num;

for(int i=0;i<num;i++)

{

*(first+i)=*(from.first+i);

last++;

}

}

template<typename T>

Myvector<T>::~Myvector()

{

delete[] first;

first=nullptr;

last=nullptr;

end=nullptr;

}

template<typename T>

Myvector<T>& Myvector<T>:: operator=(const Myvector<T>& from)

{

delete[] first;

int num=from.end-from.first;

first=new T[num];

last=first;

end=first+num;

for(int i=0;i<num;i++)

{

*(first+i)=*(from.first+i);

last++;

}

}

template<typename T>

T& Myvector<T>::at(int loc)

{

try {

if(first+loc>last)

throw(1);

else

return *(first+loc);

} catch (1) {

cout<<"out of range"<<endl;

}

}

template<typename T>

bool Myvector<T>::empty()

{

if(first==last)

return true;

else

return false;

}

template<typename T>

bool Myvector<T>::full()

{

if(end==last)

return true;

else

return false;

}

template<typename T>

T& Myvector<T>::front()

{

try {

if(empty())

throw(1);

else

return *first;

} catch (1) {

cout<<"list is empty"<<endl;

}

}

template<typename T>

T& Myvector<T>::back()

{

try {

if(empty())

throw(1);

else

return *last;

} catch (1) {

cout<<"list is empty"<<endl;

}

}

template<typename T>

int Myvector<T>::size()

{

return last-first;

}

template<typename T>

void Myvector<T>::clear()

{

last=first;

}

template<typename T>

T* Myvector<T>::expand()

{

int num=end-first;

first=memcpy(first,first,2*sizeof(T)*num);

end=first+2*num;

}

template<typename T>

void Myvector<T>::push_back(T e)

{

if(full())

expand();

*last=e;

last++;

}

template<typename T>

void Myvector<T>::pop_back()

{

try {

if(empty())

throw(1);

else

last--;

} catch (1) {

cout<<"list is empty"<<endl;

}

}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值