Set.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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. struct Iterator : public TreeIteratorBase
  52. {
  53. /// Construct.
  54. Iterator()
  55. {
  56. }
  57. /// Construct with a node pointer.
  58. Iterator(Node* ptr) :
  59. TreeIteratorBase(ptr)
  60. {
  61. }
  62. /// Preincrement the pointer.
  63. Iterator& operator ++ () { GotoNext(); return *this; }
  64. /// Postincrement the pointer.
  65. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  66. /// Predecrement the pointer.
  67. Iterator& operator -- () { GotoPrev(); return *this; }
  68. /// Postdecrement the pointer.
  69. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  70. /// Point to the key.
  71. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  72. /// Dereference the key.
  73. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  74. };
  75. /// %Set const iterator.
  76. struct ConstIterator : public TreeIteratorBase
  77. {
  78. /// Construct.
  79. ConstIterator()
  80. {
  81. }
  82. /// Construct with a node pointer.
  83. ConstIterator(Node* ptr) :
  84. TreeIteratorBase(ptr)
  85. {
  86. }
  87. // Construct from a non-const iterator.
  88. ConstIterator(const Iterator& it) :
  89. TreeIteratorBase(it.ptr_)
  90. {
  91. }
  92. /// Assign from a non-const iterator.
  93. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  94. /// Preincrement the pointer.
  95. ConstIterator& operator ++ () { GotoNext(); return *this; }
  96. /// Postincrement the pointer.
  97. ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
  98. /// Predecrement the pointer.
  99. ConstIterator& operator -- () { GotoPrev(); return *this; }
  100. /// Postdecrement the pointer.
  101. ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
  102. /// Point to the key.
  103. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  104. /// Dereference the key.
  105. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  106. };
  107. /// Construct empty.
  108. Set()
  109. {
  110. }
  111. /// Construct from another set.
  112. Set(const Set<T>& set)
  113. {
  114. allocator_ = AllocatorInitialize(sizeof(Node), set.Size() + 1);
  115. *this = set;
  116. }
  117. /// Destruct.
  118. ~Set()
  119. {
  120. Clear();
  121. if (head_)
  122. {
  123. FreeNode(reinterpret_cast<Node*>(head_));
  124. head_ = 0;
  125. }
  126. AllocatorUninitialize(allocator_);
  127. }
  128. /// Assign a set.
  129. Set& operator = (const Set<T>& set)
  130. {
  131. Clear();
  132. Insert(set);
  133. return *this;
  134. }
  135. /// Add-assign a value.
  136. Set& operator += (const T& rhs)
  137. {
  138. Insert(rhs);
  139. return *this;
  140. }
  141. /// Add-assign a set.
  142. Set& operator += (const Set<T>& rhs)
  143. {
  144. Insert(rhs);
  145. return *this;
  146. }
  147. /// Test for equality with another set.
  148. bool operator == (const Set<T>& rhs) const
  149. {
  150. if (rhs.size_ != size_)
  151. return false;
  152. ConstIterator i = Begin();
  153. ConstIterator j = rhs.Begin();
  154. while (i != End())
  155. {
  156. if (*i != *j)
  157. return false;
  158. ++i;
  159. ++j;
  160. }
  161. return true;
  162. }
  163. /// Test for inequality with another set.
  164. bool operator != (const Set<T>& rhs) const
  165. {
  166. if (rhs.size_ != size_)
  167. return true;
  168. ConstIterator i = Begin();
  169. ConstIterator j = rhs.Begin();
  170. while (i != End())
  171. {
  172. if (*i != *j)
  173. return true;
  174. ++i;
  175. ++j;
  176. }
  177. return false;
  178. }
  179. /// Clear the set.
  180. void Clear()
  181. {
  182. Node* root = Root();
  183. if (!root)
  184. return;
  185. EraseNodes(root);
  186. head_->parent_ = 0;
  187. }
  188. /// Insert a key. Return iterator to the value.
  189. Iterator Insert(const T& key) { return Iterator(InsertNode(key)); }
  190. /// Insert a set.
  191. void Insert(const Set<T>& set) { Insert(set.Begin(), set.End()); }
  192. /// Insert a key by iterator. Return iterator to the value.
  193. Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(*it)); }
  194. /// Insert a range by iterators.
  195. void Insert(const ConstIterator& start, const ConstIterator& end)
  196. {
  197. ConstIterator it = start;
  198. while (it != end)
  199. InsertNode(*it++);
  200. }
  201. /// Erase a key. Return true if was found.
  202. bool Erase(const T& key) { return EraseNode(key); }
  203. /// Erase a key by iterator.
  204. void Erase(const Iterator& it) { EraseNode(*it); }
  205. /// Erase a range by iterators.
  206. void Erase(const Iterator& start, const Iterator& end)
  207. {
  208. Iterator it = start;
  209. while (it != end)
  210. {
  211. Iterator current = it++;
  212. Erase(current);
  213. }
  214. }
  215. /// Return whether contains a key.
  216. bool Contains(const T& key) const { return FindNode(key) != 0; }
  217. /// Return iterator to the node with key, or end iterator if not found.
  218. Iterator Find(const T& key) { Node* node = FindNode(key); return node ? Iterator(node) : End(); }
  219. /// Return const iterator to the node with key, or null iterator if not found.
  220. ConstIterator Find(const T& key) const { Node* node = FindNode(key); return node ? ConstIterator(node) : End(); }
  221. /// Return iterator to the beginning.
  222. Iterator Begin() { return Iterator(FindFirst()); }
  223. /// Return const iterator to the beginning.
  224. ConstIterator Begin() const { return ConstIterator(FindFirst()); }
  225. /// Return iterator to the end.
  226. Iterator End() { return ++Iterator(FindLast()); }
  227. /// Return const iterator to the end.
  228. ConstIterator End() const { return ++ConstIterator(FindLast()); }
  229. /// Return first key.
  230. const T& Front() { return FindFirst()->key_; }
  231. /// Return last key.
  232. const T& Back() { return FindLast()->key_; }
  233. /// Return number of keys.
  234. unsigned Size() const { return size_; }
  235. /// Return whether set is empty.
  236. bool Empty() const { return size_ == 0; }
  237. private:
  238. /// Return the root node, or 0 if empty.
  239. Node* Root() const { return head_ ? reinterpret_cast<Node*>(head_->parent_) : 0; }
  240. /// Find the node with smallest key.
  241. Node* FindFirst() const
  242. {
  243. Node* node = Root();
  244. if (!node)
  245. return 0;
  246. // Search if not cached
  247. Node*& first = reinterpret_cast<Node*&>(head_->link_[0]);
  248. if (!first)
  249. {
  250. while (node && node->link_[0])
  251. node = node->Child(0);
  252. first = node;
  253. }
  254. return first;
  255. }
  256. /// Find the node with largest key.
  257. Node* FindLast() const
  258. {
  259. Node* node = Root();
  260. if (!node)
  261. return 0;
  262. // Search if not cached
  263. Node*& last = reinterpret_cast<Node*&>(head_->link_[1]);
  264. if (!last)
  265. {
  266. while (node && node->link_[1])
  267. node = node->Child(1);
  268. last = node;
  269. }
  270. return last;
  271. }
  272. /// Find a node with key. Return null if not found.
  273. Node* FindNode(const T& key) const
  274. {
  275. Node* node = Root();
  276. while (node)
  277. {
  278. if (node->key_ == key)
  279. return node;
  280. else
  281. node = node->Child(node->key_ < key);
  282. }
  283. return 0;
  284. }
  285. /// Insert a node and return a pointer to it.
  286. Node* InsertNode(const T& key)
  287. {
  288. Node* ret = 0;
  289. if (!allocator_)
  290. allocator_ = AllocatorInitialize(sizeof(Node));
  291. if (!head_)
  292. head_ = ReserveNode();
  293. if (!head_->parent_)
  294. {
  295. head_->parent_ = ret = ReserveNode(key);
  296. head_->link_[0] = head_->parent_;
  297. head_->link_[1] = head_->parent_;
  298. ++size_;
  299. }
  300. else
  301. {
  302. Node h;
  303. Node* g;
  304. Node* t;
  305. Node* p;
  306. Node* q;
  307. unsigned dir = 0;
  308. unsigned last = 0;
  309. t = &h;
  310. g = p = 0;
  311. q = reinterpret_cast<Node*>(head_->parent_);
  312. t->SetChild(1, q);
  313. for (;;)
  314. {
  315. if (!q)
  316. {
  317. p->SetChild(dir, q = ret = ReserveNode(key));
  318. ++size_;
  319. }
  320. else if (IsRed(q->link_[0]) && IsRed(q->link_[1]))
  321. {
  322. q->isRed_ = true;
  323. q->link_[0]->isRed_ = false;
  324. q->link_[1]->isRed_ = false;
  325. }
  326. if (IsRed(q) && IsRed(p))
  327. {
  328. unsigned dir2 = (t->link_[1] == g);
  329. if (q == p->link_[last])
  330. t->SetChild(dir2, RotateSingle(g, !last));
  331. else
  332. t->SetChild(dir2, RotateDouble(g, !last));
  333. }
  334. if (q->key_ == key)
  335. {
  336. ret = q;
  337. break;
  338. }
  339. last = dir;
  340. dir = q->key_ < key;
  341. if (g)
  342. t = g;
  343. g = p;
  344. p = q;
  345. q = q->Child(dir);
  346. }
  347. head_->parent_ = h.Child(1);
  348. // Invalidate cached first and last nodes
  349. head_->link_[0] = 0;
  350. head_->link_[1] = 0;
  351. }
  352. head_->parent_->isRed_ = false;
  353. head_->parent_->parent_ = 0;
  354. return ret;
  355. }
  356. /// Erase a node. Return true if was erased.
  357. bool EraseNode(const T& key)
  358. {
  359. if (!head_ || !head_->parent_)
  360. return false;
  361. Node h;
  362. Node* q;
  363. Node* p;
  364. Node* g;
  365. Node* f;
  366. unsigned dir = 1;
  367. bool removed = false;
  368. q = &h;
  369. f = g = p = 0;
  370. q->SetChild(1, head_->parent_);
  371. while (q->link_[dir])
  372. {
  373. unsigned last = dir;
  374. g = p;
  375. p = q;
  376. q = q->Child(dir);
  377. dir = q->key_ < key;
  378. if (q->key_ == key)
  379. f = q;
  380. if (!IsRed(q) && !IsRed(q->link_[dir]))
  381. {
  382. if (IsRed(q->link_[!dir]))
  383. {
  384. p->SetChild(last, RotateSingle(q, dir));
  385. p = p->Child(last);
  386. }
  387. else if (!IsRed(q->link_[!dir]))
  388. {
  389. Node* s = p->Child(!last);
  390. if (s)
  391. {
  392. if (!IsRed(s->link_[!last]) && !IsRed(s->link_[last]))
  393. {
  394. p->isRed_ = false;
  395. s->isRed_ = true;
  396. q->isRed_ = true;
  397. }
  398. else
  399. {
  400. int dir2 = (g->link_[1] == p);
  401. if (IsRed(s->link_[last]))
  402. g->SetChild(dir2, RotateDouble(p, last));
  403. else if (IsRed(s->link_[!last]))
  404. g->SetChild(dir2, RotateSingle(p, last));
  405. Node* t = g->Child(dir2);
  406. q->isRed_ = t->isRed_ = true;
  407. t->link_[0]->isRed_ = false;
  408. t->link_[1]->isRed_ = false;
  409. }
  410. }
  411. }
  412. }
  413. }
  414. if (f)
  415. {
  416. f->key_ = q->key_;
  417. p->SetChild(p->link_[1] == q, q->link_[q->link_[0] == 0]);
  418. FreeNode(q);
  419. --size_;
  420. removed = true;
  421. }
  422. head_->parent_ = h.Child(1);
  423. if (head_->parent_)
  424. {
  425. head_->parent_->isRed_ = false;
  426. head_->parent_->parent_ = 0;
  427. }
  428. // Invalidate cached first and last nodes
  429. head_->link_[0] = 0;
  430. head_->link_[1] = 0;
  431. return removed;
  432. }
  433. /// Erase the nodes recursively.
  434. void EraseNodes(Node* node)
  435. {
  436. Node* left = node->Child(0);
  437. Node* right = node->Child(1);
  438. FreeNode(node);
  439. --size_;
  440. if (left)
  441. EraseNodes(left);
  442. if (right)
  443. EraseNodes(right);
  444. }
  445. /// Reserve a node.
  446. Node* ReserveNode()
  447. {
  448. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  449. new(newNode) Node();
  450. return newNode;
  451. }
  452. /// Reserve a node with specified key.
  453. Node* ReserveNode(const T& key)
  454. {
  455. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  456. new(newNode) Node(key);
  457. return newNode;
  458. }
  459. /// Free a node.
  460. void FreeNode(Node* node)
  461. {
  462. (node)->~Node();
  463. AllocatorFree(allocator_, node);
  464. }
  465. };