首页 > 代码库 > vector容器的实现
vector容器的实现
简单实现了构造、析构、push_back、pop_back、operator=、operator[]、clear等函数
template<class T> class my_vector { private: int count; int alloc_size; T *arr; public: my_vector():count(0),alloc_size(0),arr(NULL) { } my_vector(int n, T ele): count(0),alloc_size(n) { arr = new T[n]; while(n--) { push_back(ele); } } my_vector(const my_vector &other):count(0),alloc_size(0),arr(NULL) { *this = other; } my_vector<T>& operator=(const my_vector &other) { count = other.size(); alloc_size = count; T *oldarr = arr; arr = new T[count]; for(int i = 0; i < count; i++) arr[i] = other[i]; delete []oldarr; } void push_back(T ele) { if(count == alloc_size) { T *oldarr = arr; int new_size; if(alloc_size == 0) new_size = 1; else new_size = alloc_size*2; arr = new T[new_size]; for(int i = 0; i < count; i++) { arr[i] = oldarr[i]; } alloc_size = new_size; delete []oldarr; } arr[count] = ele; count++; } void pop_back() { if(count > 0) count--; } int size() { return count; } T& operator[](int pos) { assert(pos < count); return arr[pos]; } void clear() { count = 0; } ~my_vector() { count = 0; alloc_size = 0; delete []arr; arr = NULL; } };
vector容器的实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。