学习 LLVM(13) SmallSet 类

位于 llvm/include/llvm/[[ADT]]/SmallSet.hhtml

注释:'Normally small' sets -- 普通小型集合less

这个头文件定义了 SmallSet 类。ide

SmallSet 类保持(维护)一组惟一值的集合,为集合中元素数量较少的状况(小于 N)进行了优化。这种状况下,Set 能够不用进行内存分配。若是 Set 变得更大,则内部扩展到使用 std::set 来维护以得到理想的检索响应时间。要注意的是,这个类不提供迭代器(iterator)。函数

参见:http://llvm.org/docs/ProgrammersManual.html#dss_smallset优化

SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less than N).  In this case, the set can be
maintained with no mallocs.  If the set gets large, we expand to using an std::set to maintain reasonable lookup times.this

Note that this set does not provide a way to iterate over members in the
set.code

== SmallSet 类概要 ==
orm

template <T, N, C> class SmallSet {  // 注1:T, N, C
  SmallVector<T,N> Vector;  // 内部使用 SmallVector 保存集合数据。
  std::set<T,C> Set;   // 当元素多了使用 std::set 保存集合数据。

  this() // 构造
  empty(), size(), count(), insert(), erase(), clear() 等容器方法。
}

注1:T 是要保存的元素的类型;N 是 in-place 保存的元素的数量,其实际传递给 SmallVector 模板;C 缺省为 std::less<T> 用于比较两个元素的大小,传递给 std::set 作模板参数。htm

== 实现机理 ==
咱们以 insert() 函数为例,研究其实现机理。内存

* 1. 当 std::set 非空的时候,也即 SmallVector 不足以容纳 N 个元素的时候,直接将新元素插入到 std::set 中。
* 2. 在 SmallVector 中查找(线性搜索),若是已经存在了(== 比较),则返回 false(重复不插入)
* 3. 若是 SmallVector 的现有元素数量 < N,表示还未装满,则 push_back 到 SmallVector 中。
* 4. 不然,SmallVector 已经满了,将 SmallVector 全部内容转入 std::set;而后插入到 std::set 中。这里进行了 SmallVector -> std::set 的转换。

其它的实现机理都很简单,再也不说明。

相关文章
相关标签/搜索