1. 概念
set是一种关联式容器。set是用来存储同一数据类型的数据类型,并且能从一个数据集合中取出数据,在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序(依赖于红黑树中自动排序的实现)。
2. 源码分析
以G2.9为例,以下为set的部分源码实现:
template<class Key,
class Compare = less<Key>,
class Alloc = alloc>
class set
{
public:
//typedefs
typedef Key key_type;
typedef Key value_type;
typedef Compare key_compare;
typedef Compare value_compare;
private:
typedef rb_tree<key_type, value_type,
identity<value_type>, key_compare, Alloc> rep_type;
rep_type t;
public:
typedef typename rep_type::const_iterator iterator; //const_iterator说明set的元素不可修改
...
};template<class Arg,class Result>
struct unary_function
{
typedef Arg argument_type;
typedef Result result_type;
};
//返回自身值
template<class T>
struct identity : public unary_function<T, T>
{
const T& operator() (const T& x) const { return x; }
};1) set内部采用的就是一种非常高效的平衡检索二叉树:红黑树,也成为RB树(Red-Black Tree)。RB树的统计性能要好于一般平衡二叉树,所以被STL选择作为了关联容器的内部结构;
2) set的迭代器类型为const_iterator,说明set中的元素不能被直接改变;
3) set/Multiset元素的key和value是相同的,即key就是value;
4) set元素的key必须是独一无二的,其insert调用的是rb_tree的insert_unique();
multiset元素的key是可以重复的,其insert调用的是rb_tree的insert_equal();
3. 用法总结
可参考http://cplusplus.com/reference/set/set/?kw=set
版权声明:本文为www_dong原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。