(1)内存模型及实现接口
(2) 源代码及简要注释
sort性能比较低,对100万条随机数据排序要140秒左右,原版list的sort算法仅要1.4秒
#ifndef TINY_LIST
#include <memory>
namespace tiny_stl
{
//注意:此tiny_list有四种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>
struct list_node //将数据封装为结点
{
T *data;
list_node *next;
list_node *prev;
list_node(const T& value): data(new T(value)), next(NULL), prev(NULL) { }
list_node(): data(NULL), next(NULL), prev(NULL) { }
~list_node()
{
delete data;
}
T& operator*() const //重载*,便于取数据
{
return *data;
}
};
template <typename T>
class list_iterator //list专属迭代器
{
private:
using value_type = T;
using self = list_iterator;
public:
list_node<value_type> *node; //所指向的结点
public:
list_iterator(list_node<value_type> *_node): node(_node) { }
public:
self& operator++() //前置自增
{
node = node -> next;
return *this;
}
self operator++(int) //后置自增
{
self tmp = *this;
++*this;
return tmp;
}
self& operator--() //前置自减
{
node = node -> prev;
return *this;
}
self operator--(int)//后置自减
{
self tmp = *this;
--*this;
return tmp;
}
value_type& operator*() const
{
return *(*node);
}
bool operator==(const self &it) const
{
return node == it.node;
}
bool operator!=(const self &it) const
{
return node != it.node;
}
};
template <typename T>
bool less_cmp(const T &a, const T &b) //默认小于比较运算符
{
return a < b;
}
template <typename T>
bool equal_cmp(const T &a, const T &b) //默认等于比较运算符
{
return a == b;
}
template <typename T, typename U = std::allocator<T> >
class tiny_list
{
public:
using value_type = T;
using allocator_type = U;
using size_type = size_t;
using node_type = list_node<value_type>;
private:
node_type *node; //空结点
size_type elem_size; //记录大小
static allocator_type alloc; //内存分配器,虽然没用
using iterator = list_iterator<value_type>;
private:
template <typename Input>
node_type* insert_aux(node_type *pos, const Input &first, const Input &last)
//把first到last之间的所有对象插入到pos之前