【STL】模拟实现STL中set容器

淩亂°似流年 2022-11-04 09:03 314阅读 0赞

文章目录

    1. 模拟实现set需要理解的概念
    1. 模拟实现set代码

1. 模拟实现set需要理解的概念

  • 在 STL 中的 set 容器,其底层数据结构是红黑树
  • set 中存储的数据是以 key - value 的形式存储的
  • 用户存储的数据是放在 key 中的, value 用户是无法访问的

2. 模拟实现set代码

改代码可以运行的前提是需要红黑树的模拟实现中的红黑树代码

map.hpp

  1. #pragma once
  2. #include "RBTree.hpp" // 红黑树的模拟实现
  3. // set 中防止的是
  4. template<class K>
  5. class set
  6. {
  7. typedef K ValueType;
  8. struct KOFP
  9. {
  10. const K& operator()(const ValueType& data)
  11. {
  12. return data;
  13. }
  14. };
  15. typedef RBTree<ValueType, KOFP> RBT;
  16. typedef typename RBT::iterator iterator;
  17. public:
  18. set() :_t(){ }
  19. // iterator
  20. iterator begin()
  21. {
  22. return _t.begin();
  23. }
  24. iterator end()
  25. {
  26. return _t.end();
  27. }
  28. // capacity
  29. size_t size()
  30. {
  31. return _t.size();
  32. }
  33. bool empty()
  34. {
  35. return _t.empty();
  36. }
  37. // modify
  38. pair<iterator, bool> insert(const ValueType& data)
  39. {
  40. return _t.insert(data);
  41. }
  42. void swap(set<K>& s)
  43. {
  44. _t.swap(s._t);
  45. }
  46. void clear()const
  47. {
  48. _t.clear();
  49. }
  50. iterator find(const K& key)
  51. {
  52. return _t.find(key);
  53. }
  54. private:
  55. RBT _t;
  56. };

发表评论

表情:
评论列表 (有 0 条评论,314人围观)

还没有评论,来说两句吧...

相关阅读