1 封装红黑树实现 set 和 map
1.1 对底层源码及框架分析
SGI-STL30 版本源代码中,map 和 set 的源代码在 stl_map.h/stl_set.h/stl_tree.h 等头文件中。核心部分如下:
// set
#ifndef __SGI_STL_INTERNAL_TREE_H
#include <stl_tree.h>
#endif
#include <stl_set.h>
#include <stl_multiset.h>
// map
#ifndef __SGI_STL_INTERNAL_TREE_H
#include <stl_tree.h>
#endif
#include <stl_map.h>
#include <stl_multimap.h>
// stl_set.h
template<class Key, class Compare = less<Key>, class Alloc = alloc>
class set {
public:
typedef Key key_type;
typedef Key value_type;
private:
typedef rb_tree<key_type, value_type, identity<value_type>, key_compare, Alloc> rep_type;
rep_type t; // red-black tree representing set
};
// stl_map.h
template<class Key, class , = less<Key>, Alloc = alloc>
map {
:
Key key_type;
T mapped_type;
pair< Key, T> value_type;
:
rb_tree<key_type, value_type, select1st<value_type>, key_compare, Alloc> rep_type;
rep_type t;
};
{
__rb_tree_color_type color_type;
__rb_tree_node_base* base_ptr;
color_type color;
base_ptr parent;
base_ptr left;
base_ptr right;
};
< , , , , = alloc>
rb_tree {
:
* void_pointer;
__rb_tree_node_base* base_ptr;
__rb_tree_node<Value> rb_tree_node;
rb_tree_node* link_type;
Key key_type;
Value value_type;
:
;
;
;
:
size_type node_count;
link_type header;
};
< >
: __rb_tree_node_base {
__rb_tree_node<Value>* link_type;
Value value_field;
};


