vectors包含着一系列连续存储的元素,其行为和数组类似,访问vector中的任意元素或从末尾添加元素都可以在常量级时间复杂度内完成
手动实现Myvector,包含功能:构造 析构 拷贝 at() empty() full() front() back() size() clear() expand() push_back() pop_back()
#include <iostream> using namespace std; //使用模板类 template <typename T> //接收主调函数传递过来的类型形参名 class My_vectory { private: T *first; T *last; T *end; public: //一般情况下不能使用类内申明,类外定义 //如果需要类外定义,需要重新定义模板 My_vectory(){ first = last = end = nullptr; cout<<"无参构造"<<endl; } My_vectory(int n,const T &val) { first = new T[n]; for(int i=0; i<n; i++) { first[i] = val; } last = first + n; end = first + n; cout<<"有参构造"<<endl; } ~My_vectory() { delete []first; first = last = end = nullptr; cout<<"析构函数"<<endl; } //拷贝构造函数 My_vectory(const My_vectory &other):first(new T(*(other.first))),last(new T(*(other.last))),end(new T(*(other.end))) { cout<<"拷贝构造函数"<<endl; } //拷贝赋值函数 My_vectory &operator=(const My_vectory &other) { int len = other.last-other.first; int size = other.end-other.first; first = new T[size]; for(int i=0;i<len;i++) { first[i] = other.first[i]; } last = first + len; end = first + size; cout<<"拷贝赋值函数"<<endl; return *this; } //at函数 T &at(int index) { //判断index是否在范围内 if(index<0 && index>last-first) { cout<<"该下标超出范围"<<endl; throw(-1); } else return first[index]; } //判空 bool empty() { return first == last; } //判满 bool full() { return last == end; } //返回第一个元素的函数 T front() { return *first; } //返回最后一个元素的函数 T back() { return *(last-1); } //返回表中元素个数的函数 int size() { return last-first; } //删除所有元素函数 void clear() { while(last != first) { pop_back(); } } //二倍扩充函数 void expand() { int len = end-first; T *temp = new T(2*len); memcpy(temp,first,sizeof(T)*len); delete []first; first = temp; last = first+len; end = first + 2*len; } //在末尾添加一个元素 void push_back(const T e) { //判满 if(full() == true) { cout<<"该链表已满,添加失败"<<endl; cout<<"准备二倍扩充"<<endl; expand(); } *last = e; last++; cout<<"插入成功"<<endl; } //删除最后一个元素函数 void pop_back() { //判空 if(empty() == true) { cout<<"删除失败,该链表为空"<<endl; return ; } last--; cout<<"删除成功"<<endl; } }; int main() { My_vectory<char> c1(2,'a'); //使用类模板只能显式调用,在函数名后使用<>传递实参类型 My_vectory<char> c2(c1); My_vectory<char> c3; c3 = c1; c1.push_back('b'); c1.push_back('c'); c1.push_back('d'); cout<<c1.at(1)<<endl; cout<<c1.at(3)<<endl; cout<<c1.at(4)<<endl; cout<<"表中元素个数为:"<<c1.size()<<endl; cout<<"第一个元素为:"<<c1.front()<<endl; cout<<"最后一个元素为:"<<c1.back()<<endl; //调用在末尾删除函数 c1.pop_back(); cout<<"表中元素个数为:"<<c1.size()<<endl; //清空 c1.clear(); cout<<"表中元素个数为:"<<c1.size()<<endl; return 0; }
C++day7(手动实现Myvector)(使用类模板)
最新推荐文章于 2024-06-02 11:17:45 发布