简易vector的实现
2015-09-02 23:38
309 查看
在这里我们实现了一个简易的vector,没有利用到 stl中的内存分配器,内存分配利用的是new进行分配。其余功能大致实现 1 #ifndef _NVECTOR_
#define _NVECTOR_ #include<cstddef> #include <algorithm> template<typename T> class nvector{ public: typedef T value_type; typedef value_type* pointer; typedef value_type& reference; typedef value_type* iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; private: iterator start; //迭代器的起始位置 iterator finish; iterator end_of_storage; void insert_aux(iterator position, const T& value); public: iterator begin(){return start;} iterator end(){return finish;} size_type size(){return size_type(end()-begin());} size_type capacity(){return size_type(end_of_storage-begin());} bool empty(){return start==finish;} reference operator [](size_type index){return *(begin()+index);} nvector():start(0),finish(0),end_of_storage(0){} nvector(size_type n, const T& value){ start = new T[n+1]; for(int i=0;i<n;i++) start[i] = value; finish = start+n; end_of_storage = start+n; } explicit nvector(size_type n){start = new T[n+1];finish = start; end_of_storage = start+n;} ~nvector(){if(start!=NULL) delete[] start;finish=0;end_of_storage = 0;} reference front(){return *begin();} reference back(){return *(end()-1);} void push_back(const T& value){ if(finish!=end_of_storage){ *finish = value; ++finish; }else insert_aux(finish, value); } void pop_back(){ if(!empty()){ *finish->~T(); --finish; } } void clear(){ finish = start; } }; template<typename T> void nvector<T>::insert_aux(iterator position,const T& value){ if(finish!=end_of_storage){ T x_copy = value; copy_backward(position,finish,finish+1); finish++; *position = x_copy; }else{ const size_type old_size = size(); const size_type new_size = old_size!=0?2*old_size:1; iterator new_start = new T[new_size]; iterator new_finish = copy(start,position,new_start); T x_copy = value; *new_finish = x_copy; ++new_finish; new_finish = copy(position,finish,new_finish); if(start!=NULL) delete[] start; start = new_start; finish = new_finish; end_of_storage = start+new_size; } } #endif
相关文章推荐
- java的自动装箱和拆箱
- rtp丢包重传demo
- 设计模式-结构型之享元模式
- android:数据的存储与访问----文件方法
- iOS---内存分析
- 放苹果
- 创建层次二叉树
- 【poj1011】木棒
- 发送邮件代码
- C#编程总结(四)多线程应用
- 使用Ccscan进行数据字符集转换验证(上)
- 【LeetCode】141 Linked List Cycle (java实现)
- C#编程总结(五)多线程带给我们的一些思考
- C++ this指针
- uva 1108 - Mining Your Own Business(强连通)
- 后缀数组LCP + 二分 - UVa 11107 Life Forms
- c语言一维数组的定义、初始化
- Android ListView性能优化,异步加载图片
- Mac工具
- C#编程总结(六)异步编程