STL源码剖析——rb_tree, map, set

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

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值