改造红黑树
关联式容器存储的是K, V键值对,故在改造红黑树时,K为key类型,对于V来说,如果是set,则其为K类型,如果是map则为pair<K, V>
,类型,除此之外,还需要一个仿函数类KeyOfValue来兼容map与set的大小比较,其迭代器也需要封装指针为一个类,迭代器的自加自减相当于红黑树的中序遍历
template <class V>
struct RBTIterator
{
typedef RBNode<V> Node;
typedef RBTIterator<V> Self;
RBTIterator(Node* node);
V& operator*();
V* operator->();
bool operator!=(const Self& it);
bool operator==(const Self& it);
Self& operator++();
Self operator++(int);
Self& operator--();
Self operator--(int);
private:
void add();
void sub();
Node* _node;
};
template <class K, class V, class KeyOfValue>
class RBTree
{
public:
typedef RBNode<V> Node;
typedef RBTIterator<V> iterator;
iterator begin();
iterator end();
RBTree();
bool empty();
pair<iterator, bool> insert(const V& val);
iterator Find(const K& data);
size_t size();
Node* leftMost();
Node* rightMost();
void RotateL(Node* parent);
void RotateR(Node* parent);
private:
Node* _header;
};
map和set的实现
通过封装红黑树类,传入仿函数类和具体类型,修改等操作调用红黑树的接口,遍历操作通过迭代器完成
template <class K, class V>
class Map
{
public:
struct MapKeyOfValue
{
const K& operator()(const pair<K, V>& value)
{
return value.first;
}
};
typedef typename RBTree<K, pair<K, V>, MapKeyOfValue>::iterator iterator;
iterator begin()
{
return _rbt.begin();
}
iterator end()
{
return _rbt.end();
}
bool empty()
{
return _rbt->empty();
}
size_t size()
{
return _rbt.size();
}
pair<iterator, bool> insert(const pair<K, V>& value)
{
return _rbt.insert(value);
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = _rbt.insert(make_pair(key, V()));
return ret.first->second;
}
iterator find(const K& key)
{
return _rbt.Find(pair<K, V>(key, V()));
}
private:
RBTree<K, pair<K, V>, MapKeyOfValue> _rbt;
};
template <class K>
class Set
{
struct SetKeyOfValue
{
const K& operator()(const K& key)
{
return key;
}
};
public:
typedef typename RBTree<K, K, SetKeyOfValue>::iterator iterator;
iterator begin()
{
return _rbt.begin();
}
iterator end()
{
return _rbt.end();
}
bool empty()
{
return _rbt.empty();
}
iterator find(const K& key)
{
return _rbt.Find(key);
}
size_t size()
{
return _rbt.size();
}
pair<iterator, bool> insert(const K& key)
{
return _rbt.insert(key);
}
private:
RBTree<K, K, SetKeyOfValue> _rbt;
};