您的位置:首页 > 其它

简易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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: