Map.h 16 KB

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