Set.h 16 KB

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