stl源码剖析 详细学习笔记deque(2)

时间:2021-02-14 22:26:02

//---------------------------15/3/13----------------------------

self&operator++()

{

++cur;

if(cur==last)

{

set_node(node+);

cur=first;

}

return *this;

}

self operator++(int)   //这里不能返回引用,因为
tmp是临时变量,作用域结束tmp就消失了

{

self tmp=*this;

++*this;

return tmp;

}

self&operator--()

{

if(cur=first)

{

set_node(node-);

cur=last;

}

--cur;

return *this;

}

selfoperator--(int)

{

self tmp=*this;

--*this;

return temp;

}

/*

1.看能否在不改变node的情况下进行指针位置的移动

2.调整node

offset==(n+x) -->>
最后的位置==first + (n + x)

x代表cur
距离first的距离,也就是cur当前的下标

(offset>0): offset/diffenrence_type(buffer_size())

-->>    y==(n + x)/(sz) -->>移动的node节点个数为y

(offset<0)   -difference_type((-offset -1) / buffer_size()) - 1

-->>    y==-(-n - x -1)/(sz) -1 -->> y==(n + x +1)/(sz) -1

不同于(offset<0)的情况,因为当前处于first位置,移动的距离在

-1到-(sz)是都应该移动一个node节点所以才取上式子;

3.调整cur

(offset>0) :offset==(n + x)

node_offset*difference_type(buffer_size())==(n + x -r)

(r代表余数)

-->>z(位移量)==r

(offset<0)  :offset==(n + x)

node_offset*difference_type(buffer_size())==(n + x +r-sz)

-->>z(位移量)==-sz + r

cur =z

*/

self&operator+=(difference_type n)

{

difference_type offset =n+(cur - first);

if(offset >=
&& offset < difference_type(buffer_size()))

cur+=n;

else

{

difference_type node_offset=

offset > ? offset/difference_type(buffer_size())

: -difference_type((-offset -) / buffer_size()) - ;

set_node(node + node_offset);

cur = first +(offset - node_offset * difference_type(buffer_size()));

}

return *this;

}

selfoperator+(difference_type n)
const

{

self tmp=*this;

return tmp+=n;

}

self &operator -=(difference_type n){return *this +=-n;}

selfoperator-(difference_type n)
const

{

self tmp =*this;

return tmp-=n;

}

referenceoperator[](difference_type)const{return *(*this
+n);}

bool
operator==(const  self& x)const{return cur==x.cur;}

bool
operator!=(const self& x)const {return !(*this==x);}

bool
operator<(const self& x)const

{

return (node==x.node)?(cur < x.cur) :(node < x.node);

}

>

class deque

{

public:

typedef T value_type;

typedef value_type* pointer;

typedef size_t size_type;

typedef __deque_iterator<T,T&,T*,BufSiz> iteratoer;

protected:

typedef pointer* map_pointer;

iteratoer start;

iteratoer finish;

map_pointer map;

size_type map_size;

public:

iteratoer begin(){return start;}

iteratoer end() {return finish;}

referenceoperator[](size_type n)

{

return start[difference_type(n)];

}

reference front(){return *start;}

reference back()

{

iteratoer tmp=finish;

--tmp;

return *tmp;

//上面三行不改为 return *(finish-1)是因为operator -(difference_type n)

//   
的操作比--复杂很多

}

size_type size()const {return finish - start;;}//两个;是手误??

}