Set.h 15 KB

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