(1)内存模型及实现接口
(2)源代码及简要注释
push_back、pop_back、push_front、pop_front性能和原版deque相当,insert性能慢1倍
#ifndef TINY_DEQUE
#include <memory>
#include <cmath>
#include <cstring>
namespace tiny_stl
{
//注意:此tiny_deque有四种insert版本
//其中
//template <typename Input>
//iterator insert(const iterator& pos, const Input &first, const Input &last)
//和
//iterator insert(const iterator& pos, size_type count, const value_type& value)
//可能会发生重载冲突,如果value_type = int
template <typename T, int BUFFER_SIZE>
class deque_iterator
//deque专属迭代器,在用户看来是连续内存块上的双向迭代器,实际上游走于多个同等大小的连续内存块上
{
public:
using value_type = T;
using self = deque_iterator;
using size_type = size_t;
value_type *first; //所在内存块的首地址
value_type *last; //所在内存块的尾后地址
value_type *cur; //在内存块上的精确位置
value_type **node; //指向map数组中的一个位置,用于在内存块之间移动
private:
void set_node(value_type **_node) //迭代器跳转到另一个内存块
{
node = _node;
first = *_node;
last = first + BUFFER_SIZE;
}
public:
self& operator++() //前置自增
{
++cur;
if(cur == last)
{
set_node(node + 1);
cur = first;
}
return *this;
}
self operator++(int) //后置自增
{
self tmp = *this;
++*this;
return tmp;
}
self& operator--() //前置自减
{
if(cur == first)
{
set_node(node - 1);
cur = last;
}
--cur;
return *this;
}
self operator--(int) //后置自减
{
self tmp = *this;
--*this;
return tmp;
}
self& operator+=(int n)
{
int offset = n + (cur - first);
int node_offset = floor(static_cast<double>(offset)/BUFFER_SIZE);
set_node(node + node_offset);
//如果是负数求余,则编译器计算-9%4 应等于-1,而非-3,否则此处应修改
int cur_offset = (offset % BUFFER_SIZE + BUFFER_SIZE) % BUFFER_SIZE;
cur = first + cur_offset;
return *this;
}
self& operator-=(int n)
{
operator+=(-n);
return *this;
}
self operator+(int n) const
//仅实现了 iterator + n的运算形式,n + iterator未实现,减运算一样
{
self tmp = *this;
tmp += n;
return tmp;
}
self operator-(int n) const
{
self tmp = *this;
tmp -= n;
return tmp;
}
int operator-(const self &it) const
{
if(node == it.node)
{
return cur - it.cur;
}
else if(node > it.node)
{
return (node - it.node - 1) * BUFFER_SIZE + (cur - first) + (it.last - it.cur);
}
else
{
return -((it.node - node - 1) * BUFFER_SIZE + (it.cur - it.first) + (last - cur));
}
}
bool operator<(const self &it) const
{
if(node < it.node || (node == it.node && cur < it.cur))
{
return true;
}
return false;
}
bool operator>(const self &it) const
{
return it < *this;
}
bool operator==(const self &it) const
{
return cur == it.cur;
}
bool operator!=(const self &it) const
{
return cur != it.cur;
}
bool operator>=(const self &it) const
{
return it < *this || it == *this;
}
bool operator<=(const self &it) const
{
return *this < it || *this == it;
}
value_type& operator*() const
{
return *cur;
}
};
template <typename T, typename U = std::allocator<T> >
class tiny_deque
{
public:
using value_type = T;
using allocator_type = U;
using size_type = size_t;
private:
static const int BUFFER_SIZE = 20; //默认内存块大小
static allocator_type alloc; //内存分配器
value_type **map_start; //map数组的起始地址,map数组用于记录分散的内存块的起始地址
size_type map_size; //map数组大小
valu