仿照vector手动实现自己的myVector,最主要实现二倍扩容功能
- #include
-
- using namespace std;
- template <typename T>
- class Myvector
- {
- private:
- T *start;//起始指针
- T *end;//数组末尾指针
- T *last;//数组有效长度的尾指针
- public:
- //定义无参构造
- Myvector(){
- start=new T[2];
- last=start;
- end=start+1;
- }
- //定义有参构造
- Myvector(int num,const T &val)
- {
- start=new T[num+1];
- last=start;
- end=start+num;
- for(int i=0;i
- {
- start[i]=val;
- last++;
- }
-
- }
- //定义拷贝构造函数
- Myvector(const Myvector
*other) - {
- this->start=new T[other->end -other->first+1];
- this->last=other->last;
- this->end=other->end;
- for(int i=0;i
end-other->start;++i) - {
- this->first[i]=other->first[i];
- }
- }
- //定义拷贝赋值函数
- Myvector &operator=(const Myvector
*other){ - if(this!=other)
- {
- delete []start;
- this->first=new T[other->end-other->start+1];
- this->last=other->last;
- this->end=other->end;
- for(int i=0;i
end-other->start;i++) - {
- this->start[i]=other->start[i];
- }
- }
- return *this;
- }
- //析构函数
- ~Myvector()
- {
- delete []start;
- start=nullptr;
- last=nullptr;
- end=nullptr;
- }
- //at()函数
- T &at(int pos){
- if(pos>end-start)
- {
- cout<<"越界了"<
- }
- return start[pos];
- }
- //判空
- bool empty(){
- if(last==start)
- {
- return 1;
- }else{return 0;}
- }
- //front()函数
- T &front(){
- return *start;
- }
- //back()函数
- T &back(){
- return *(end-1);
- }
- //size()函数
- int size()
- {
- return last-start;
- }
- //二倍扩容
- void erkr(){
- if(end-start==1||last==start)
- {
-
-
- int len=end-start;
- start=new T[len*2];
- }
- last+=(end-start)-1;
- return;
- }
- //push_back()
- void push_back(const T &val)
- {
- if(last==end)//容器满了
- {
- erkr();
- }
- *last=val;
- last++;
-
- }
- //pop_back()
- void pop_back()//容器是空的
- {
- if(empty())
- {
- cout<<"容器空了"<
- }
- last--;
- }
-
- //begin()返回第一个元素的迭代器
- T*begin()const{
- return start;
- }
- //end()
- T*pend(){
- return last;
- }
-
- };
- int main()
- {
- Myvector<int>m(2,5);
- cout<
at(1)< - cout<
size()<//大小 - m.push_back(6);
- cout<
size()<//大小 - Myvector<int>n(m);
- n.pop_back();
-
-
相关阅读:
mysql
旧电脑升级记录
数组扁平化(es6)
【HTML】HTML基础系列文章小小总结,运用标签写出网页!
七夕节送什么礼物?推荐女生喜欢的礼物
Sophos Firewall OS (SFOS) 19.0 GA
JavaScript事件之拖拽事件(详解)
URP渲染管线场景优化实战 1.1 预配置及初始信息
OSG第三方库编译之三十六:exiv2编译(Windows、Linux、Macos环境下编译)
人脸识别测试数据分析
-
原文地址:https://blog.csdn.net/HYL1234511/article/details/132890509