Set.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "TreeBase.h"
  25. // Based on Red Black Trees by Julienne Walker
  26. // http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx
  27. /// %Set template class using a red-black tree.
  28. template <class T> class Set : public TreeBase
  29. {
  30. public:
  31. /// %Set node.
  32. struct Node : public TreeNodeBase
  33. {
  34. // Construct undefined.
  35. Node()
  36. {
  37. }
  38. // Construct with key.
  39. Node(const T& key) :
  40. key_(key)
  41. {
  42. }
  43. /// Key.
  44. T key_;
  45. /// Return parent node.
  46. Node* Parent() const { return static_cast<Node*>(parent_); }
  47. /// Return the left or right child.
  48. Node* Child(unsigned dir) const { return static_cast<Node*>(link_[dir]); }
  49. };
  50. /// %Set iterator.
  51. class Iterator : public TreeIteratorBase
  52. {
  53. public:
  54. /// Construct.
  55. Iterator()
  56. {
  57. }
  58. /// Construct with a node pointer.
  59. Iterator(Node* ptr) :
  60. TreeIteratorBase(ptr)
  61. {
  62. }
  63. /// Preincrement the pointer.
  64. Iterator& operator ++ () { GotoNext(); return *this; }
  65. /// Postincrement the pointer.
  66. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  67. /// Predecrement the pointer.
  68. Iterator& operator -- () { GotoPrev(); return *this; }
  69. /// Postdecrement the pointer.
  70. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  71. /// Point to the key.
  72. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  73. /// Dereference the key.
  74. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  75. };
  76. /// %Set const iterator.
  77. class ConstIterator : public TreeIteratorBase
  78. {
  79. public:
  80. /// Construct.
  81. ConstIterator()
  82. {
  83. }
  84. /// Construct with a node pointer.
  85. ConstIterator(Node* ptr) :
  86. TreeIteratorBase(ptr)
  87. {
  88. }
  89. // Construct from a non-const iterator.
  90. ConstIterator(const Iterator& it) :
  91. TreeIteratorBase(it.ptr_)
  92. {
  93. }
  94. /// Assign from a non-const iterator.
  95. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  96. /// Preincrement the pointer.
  97. ConstIterator& operator ++ () { GotoNext(); return *this; }
  98. /// Postincrement the pointer.
  99. ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
  100. /// Predecrement the pointer.
  101. ConstIterator& operator -- () { GotoPrev(); return *this; }
  102. /// Postdecrement the pointer.
  103. ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
  104. /// Point to the key.
  105. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  106. /// Dereference the key.
  107. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  108. };
  109. /// Construct empty.
  110. Set()
  111. {
  112. }
  113. /// Construct from another set.
  114. Set(const Set<T>& set)
  115. {
  116. allocator_ = AllocatorInitialize(sizeof(Node), set.Size());
  117. *this = set;
  118. }
  119. /// Destruct.
  120. ~Set()
  121. {
  122. Clear();
  123. AllocatorUninitialize(allocator_);
  124. }
  125. /// Assign a set.
  126. Set& operator = (const Set<T>& set)
  127. {
  128. Clear();
  129. Insert(set);
  130. return *this;
  131. }
  132. /// Add-assign a value.
  133. Set& operator += (const T& rhs)
  134. {
  135. Insert(rhs);
  136. return *this;
  137. }
  138. /// Add-assign a set.
  139. Set& operator += (const Set<T>& rhs)
  140. {
  141. Insert(rhs);
  142. return *this;
  143. }
  144. /// Test for equality with another set.
  145. bool operator == (const Set<T>& rhs) const
  146. {
  147. if (rhs.size_ != size_)
  148. return false;
  149. ConstIterator i = Begin();
  150. ConstIterator j = rhs.Begin();
  151. while (i != End())
  152. {
  153. if (*i != *j)
  154. return false;
  155. ++i;
  156. ++j;
  157. }
  158. return true;
  159. }
  160. /// Test for inequality with another set.
  161. bool operator != (const Set<T>& rhs) const
  162. {
  163. if (rhs.size_ != size_)
  164. return true;
  165. ConstIterator i = Begin();
  166. ConstIterator j = rhs.Begin();
  167. while (i != End())
  168. {
  169. if (*i != *j)
  170. return true;
  171. ++i;
  172. ++j;
  173. }
  174. return false;
  175. }
  176. /// Clear the set.
  177. void Clear()
  178. {
  179. Node* root = Root();
  180. if (!root)
  181. return;
  182. EraseNodes(root);
  183. root_ = 0;
  184. }
  185. /// Insert a key. Return iterator to the value.
  186. Iterator Insert(const T& key) { return Iterator(InsertNode(key)); }
  187. /// Insert a set.
  188. void Insert(const Set<T>& set) { Insert(set.Begin(), set.End()); }
  189. /// Insert a key by iterator. Return iterator to the value.
  190. Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(*it)); }
  191. /// Insert a range by iterators.
  192. void Insert(const ConstIterator& start, const ConstIterator& end)
  193. {
  194. ConstIterator it = start;
  195. while (it != end)
  196. InsertNode(*it++);
  197. }
  198. /// Erase a key. Return true if was found.
  199. bool Erase(const T& key) { return EraseNode(key); }
  200. /// Erase a key by iterator.
  201. void Erase(const Iterator& it) { EraseNode(*it); }
  202. /// Erase a range by iterators.
  203. void Erase(const Iterator& start, const Iterator& end)
  204. {
  205. Iterator it = start;
  206. while (it != end)
  207. {
  208. Iterator current = it++;
  209. Erase(current);
  210. }
  211. }
  212. /// Return whether contains a key.
  213. bool Contains(const T& key) const { return FindNode(key) != 0; }
  214. /// Return iterator to the node with key, or end iterator if not found.
  215. Iterator Find(const T& key) { Node* node = FindNode(key); return node ? Iterator(node) : End(); }
  216. /// Return const iterator to the node with key, or null iterator if not found.
  217. ConstIterator Find(const T& key) const { Node* node = FindNode(key); return node ? ConstIterator(node) : End(); }
  218. /// Return iterator to the beginning.
  219. Iterator Begin() { return Iterator(FindFirst()); }
  220. /// Return const iterator to the beginning.
  221. ConstIterator Begin() const { return ConstIterator(FindFirst()); }
  222. /// Return iterator to the end.
  223. Iterator End() { return ++Iterator(FindLast()); }
  224. /// Return const iterator to the end.
  225. ConstIterator End() const { return ++ConstIterator(FindLast()); }
  226. /// Return first key.
  227. const T& Front() { return FindFirst()->key_; }
  228. /// Return last key.
  229. const T& Back() { return FindLast()->key_; }
  230. /// Return number of keys.
  231. unsigned Size() const { return size_; }
  232. /// Return whether set is empty.
  233. bool Empty() const { return size_ == 0; }
  234. private:
  235. /// Return the root pointer with correct type.
  236. Node* Root() const { return reinterpret_cast<Node*>(root_); }
  237. /// Find the node with smallest key.
  238. Node* FindFirst() const
  239. {
  240. Node* node = Root();
  241. while (node && node->link_[0])
  242. node = node->Child(0);
  243. return node;
  244. }
  245. /// Find the node with largest key.
  246. Node* FindLast() const
  247. {
  248. Node* node = Root();
  249. while (node && node->link_[1])
  250. node = node->Child(1);
  251. return node;
  252. }
  253. /// Find a node with key. Return null if not found.
  254. Node* FindNode(const T& key) const
  255. {
  256. Node* node = Root();
  257. while (node)
  258. {
  259. if (node->key_ == key)
  260. return node;
  261. else
  262. node = node->Child(node->key_ < key);
  263. }
  264. return 0;
  265. }
  266. /// Insert a node and return a pointer to it.
  267. Node* InsertNode(const T& key)
  268. {
  269. Node* ret = 0;
  270. if (!root_)
  271. {
  272. root_ = ret = ReserveNode(key);
  273. ++size_;
  274. }
  275. else
  276. {
  277. Node head;
  278. Node* g, * t, * p, * q;
  279. unsigned dir = 0;
  280. unsigned last = 0;
  281. t = &head;
  282. g = p = 0;
  283. q = Root();
  284. t->SetChild(1, Root());
  285. for (;;)
  286. {
  287. if (!q)
  288. {
  289. p->SetChild(dir, q = ret = ReserveNode(key));
  290. ++size_;
  291. }
  292. else if (IsRed(q->link_[0]) && IsRed(q->link_[1]))
  293. {
  294. q->isRed_ = true;
  295. q->link_[0]->isRed_ = false;
  296. q->link_[1]->isRed_ = false;
  297. }
  298. if (IsRed(q) && IsRed(p))
  299. {
  300. unsigned dir2 = (t->link_[1] == g);
  301. if (q == p->link_[last])
  302. t->SetChild(dir2, RotateSingle(g, !last));
  303. else
  304. t->SetChild(dir2, RotateDouble(g, !last));
  305. }
  306. if (q->key_ == key)
  307. {
  308. ret = q;
  309. break;
  310. }
  311. last = dir;
  312. dir = q->key_ < key;
  313. if (g)
  314. t = g;
  315. g = p;
  316. p = q;
  317. q = q->Child(dir);
  318. }
  319. root_ = head.Child(1);
  320. }
  321. root_->isRed_ = false;
  322. root_->parent_ = 0;
  323. return ret;
  324. }
  325. /// Erase a node. Return true if was erased.
  326. bool EraseNode(const T& key)
  327. {
  328. if (!root_)
  329. return false;
  330. Node head;
  331. Node* q, * p, *g;
  332. Node* f = 0;
  333. unsigned dir = 1;
  334. bool removed = false;
  335. q = &head;
  336. g = p = 0;
  337. q->SetChild(1, Root());
  338. while (q->link_[dir])
  339. {
  340. unsigned last = dir;
  341. g = p;
  342. p = q;
  343. q = q->Child(dir);
  344. dir = q->key_ < key;
  345. if (q->key_ == key)
  346. f = q;
  347. if (!IsRed(q) && !IsRed(q->link_[dir]))
  348. {
  349. if (IsRed(q->link_[!dir]))
  350. {
  351. p->SetChild(last, RotateSingle(q, dir));
  352. p = p->Child(last);
  353. }
  354. else if (!IsRed(q->link_[!dir]))
  355. {
  356. Node* s = p->Child(!last);
  357. if (s)
  358. {
  359. if (!IsRed(s->link_[!last]) && !IsRed(s->link_[last]))
  360. {
  361. p->isRed_ = false;
  362. s->isRed_ = true;
  363. q->isRed_ = true;
  364. }
  365. else
  366. {
  367. int dir2 = (g->link_[1] == p);
  368. if (IsRed(s->link_[last]))
  369. g->SetChild(dir2, RotateDouble(p, last));
  370. else if (IsRed(s->link_[!last]))
  371. g->SetChild(dir2, RotateSingle(p, last));
  372. Node* t = g->Child(dir2);
  373. q->isRed_ = t->isRed_ = true;
  374. t->link_[0]->isRed_ = false;
  375. t->link_[1]->isRed_ = false;
  376. }
  377. }
  378. }
  379. }
  380. }
  381. if (f)
  382. {
  383. f->key_ = q->key_;
  384. p->SetChild(p->link_[1] == q, q->link_[q->link_[0] == 0]);
  385. FreeNode(q);
  386. --size_;
  387. removed = true;
  388. }
  389. root_ = head.Child(1);
  390. if (root_)
  391. {
  392. root_->isRed_ = false;
  393. root_->parent_ = 0;
  394. }
  395. return removed;
  396. }
  397. /// Erase the nodes recursively.
  398. void EraseNodes(Node* node)
  399. {
  400. Node* left = node->Child(0);
  401. Node* right = node->Child(1);
  402. FreeNode(node);
  403. --size_;
  404. if (left)
  405. EraseNodes(left);
  406. if (right)
  407. EraseNodes(right);
  408. }
  409. /// Reserve a node.
  410. Node* ReserveNode()
  411. {
  412. if (!allocator_)
  413. allocator_ = AllocatorInitialize(sizeof(Node));
  414. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  415. new(newNode) Node();
  416. return newNode;
  417. }
  418. /// Reserve a node with specified key.
  419. Node* ReserveNode(const T& key)
  420. {
  421. if (!allocator_)
  422. allocator_ = AllocatorInitialize(sizeof(Node));
  423. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  424. new(newNode) Node(key);
  425. return newNode;
  426. }
  427. /// Free a node.
  428. void FreeNode(Node* node)
  429. {
  430. (node)->~Node();
  431. AllocatorFree(allocator_, node);
  432. }
  433. };