AVL树
左右子树高度差<1
rb_tree
规则:
- 节点:
header作为额外的父节点,不存放数据
初始化时,header为红色
插入元素后,header和root互为各自的父节点
- 迭代器:
bidirectional iterator
模板参数KeyOfValue:如何取出key
set:使用identity<value_type>
map:使用select1st<value_type>
template <class Key, class Value, class KeyOfValue, class Compare, class Alloc = alloc>
class rb_tree {
protected:
size_type node_count;
link_type header;
Compare key_compare;
public:
typedef __rb_tree_iterator<value_type, referene, pointer> iterator;
private:
void init() {
header = get_node();
color(header) = __rb_tree_red;
root() = 0;
leftmost() = header; //令header左子节点为自己
rightmost() = header; //令header右子节点为自己
}
...
public:
//两种插入方式
pair<iterator, bool> insert_unique(const value_type& x); //key不能重复插入
Iterator insert_equal(const value_type& x); //key能重复插入
Iterator find(const Key &key); //查找
}
set
不能通过迭代器改变元素值
添加删除元素别的迭代器依然有效
template <class Key, class T, class Compare = less<Key>, class Alloc = alloc>
class map{
private:
typedef rb_tree<key_type, value_type, select1st<value_type>, key_compare, Alloc> rep_type;
rep_type t; //采用红黑树实现
public:
//采用insert_unique实现insert
//如果不存在则插入一个并默认初始化value
T& operator[] (const key_type &k) {
return (*((insert(value_type(k, T()))).first)).second;
}
};
map
不能通过迭代器修改key值
添加删除元素别的迭代器依然有效
template <class Key, class Compare = less<Key>, class Alloc = alloc>
class set {
private:
typedef rb_tree<key_type, value_type, identity<value_type>, key_compare, Alloc> rep_type;
rep_type t; //采用红黑树实现
public:
//采用insert_unique实现insert
...
};
multimap/multiset
与map, set区别:采用insert_equal实现insert,允许重复key