Map.h 16 KB

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