CCMap.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /****************************************************************************
  2. Copyright (c) 2013-2017 Chukong Technologies
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #ifndef __CCMAP_H__
  21. #define __CCMAP_H__
  22. #define USE_STD_UNORDERED_MAP 1
  23. #include "base/ccMacros.h"
  24. #include "base/CCRef.h"
  25. #include <vector>
  26. #if USE_STD_UNORDERED_MAP
  27. #include <unordered_map>
  28. #else
  29. #include <map>
  30. #endif
  31. /**
  32. * @addtogroup base
  33. * @{
  34. */
  35. NS_CC_BEGIN
  36. /**
  37. * Similar to std::unordered_map, but it will manage reference count automatically internally.
  38. * Which means it will invoke Ref::retain() when adding an element, and invoke Ref::release() when removing an element.
  39. * @warning The element should be `Ref` or its sub-class.
  40. * @js NA
  41. * @lua NA
  42. */
  43. template <class K, class V>
  44. class Map
  45. {
  46. public:
  47. #if USE_STD_UNORDERED_MAP
  48. typedef std::unordered_map<K, V> RefMap;
  49. #else
  50. typedef std::map<K, V> RefMap;
  51. #endif
  52. // ------------------------------------------
  53. // Iterators
  54. // ------------------------------------------
  55. /** Iterator, can be used to loop the Map. */
  56. typedef typename RefMap::iterator iterator;
  57. /** Const iterator, can be used to loop the Map. */
  58. typedef typename RefMap::const_iterator const_iterator;
  59. /** Return iterator to beginning. */
  60. iterator begin() { return _data.begin(); }
  61. /** Return const_iterator to beginning. */
  62. const_iterator begin() const { return _data.begin(); }
  63. /** Return iterator to end.*/
  64. iterator end() { return _data.end(); }
  65. /** Return const_iterator to end.*/
  66. const_iterator end() const { return _data.end(); }
  67. /** Return const_iterator to beginning.*/
  68. const_iterator cbegin() const { return _data.cbegin(); }
  69. /** Return const_iterator to end.*/
  70. const_iterator cend() const { return _data.cend(); }
  71. /** Default constructor */
  72. Map<K, V>()
  73. : _data()
  74. {
  75. static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
  76. CCLOGINFO("In the default constructor of Map!");
  77. }
  78. /** Constructor with capacity. */
  79. explicit Map<K, V>(ssize_t capacity)
  80. : _data()
  81. {
  82. static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
  83. CCLOGINFO("In the constructor with capacity of Map!");
  84. _data.reserve(capacity);
  85. }
  86. /** Copy constructor. */
  87. Map<K, V>(const Map<K, V>& other)
  88. {
  89. static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
  90. CCLOGINFO("In the copy constructor of Map!");
  91. _data = other._data;
  92. addRefForAllObjects();
  93. }
  94. /** Move constructor. */
  95. Map<K, V>(Map<K, V>&& other)
  96. {
  97. static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
  98. CCLOGINFO("In the move constructor of Map!");
  99. _data = std::move(other._data);
  100. }
  101. /**
  102. * Destructor.
  103. * It will release all objects in map.
  104. */
  105. ~Map<K, V>()
  106. {
  107. CCLOGINFO("In the destructor of Map!");
  108. clear();
  109. }
  110. /** Sets capacity of the map. */
  111. void reserve(ssize_t capacity)
  112. {
  113. #if USE_STD_UNORDERED_MAP
  114. _data.reserve(capacity);
  115. #endif
  116. }
  117. /** Returns the number of buckets in the Map container. */
  118. ssize_t bucketCount() const
  119. {
  120. #if USE_STD_UNORDERED_MAP
  121. return _data.bucket_count();
  122. #else
  123. return 0;
  124. #endif
  125. }
  126. /** Returns the number of elements in bucket n. */
  127. ssize_t bucketSize(ssize_t n) const
  128. {
  129. #if USE_STD_UNORDERED_MAP
  130. return _data.bucket_size(n);
  131. #else
  132. return 0;
  133. #endif
  134. }
  135. /** Returns the bucket number where the element with key k is located. */
  136. ssize_t bucket(const K& k) const
  137. {
  138. #if USE_STD_UNORDERED_MAP
  139. return _data.bucket(k);
  140. #else
  141. return 0;
  142. #endif
  143. }
  144. /** The number of elements in the map. */
  145. ssize_t size() const
  146. {
  147. return _data.size();
  148. }
  149. /**
  150. * Returns a bool value indicating whether the map container is empty, i.e. whether its size is 0.
  151. * @note This function does not modify the content of the container in any way.
  152. * To clear the content of an array object, member function unordered_map::clear exists.
  153. */
  154. bool empty() const
  155. {
  156. return _data.empty();
  157. }
  158. /** Returns all keys in the map. */
  159. std::vector<K> keys() const
  160. {
  161. std::vector<K> keys;
  162. if (!_data.empty())
  163. {
  164. keys.reserve(_data.size());
  165. for (const auto& iter : _data)
  166. {
  167. keys.push_back(iter.first);
  168. }
  169. }
  170. return keys;
  171. }
  172. /** Returns all keys that matches the object. */
  173. std::vector<K> keys(V object) const
  174. {
  175. std::vector<K> keys;
  176. if (!_data.empty())
  177. {
  178. keys.reserve(_data.size() / 10);
  179. for (const auto& iter : _data)
  180. {
  181. if (iter.second == object)
  182. {
  183. keys.push_back(iter.first);
  184. }
  185. }
  186. }
  187. keys.shrink_to_fit();
  188. return keys;
  189. }
  190. /**
  191. * Returns a reference to the mapped value of the element with key k in the map.
  192. *
  193. * @note If key does not match the key of any element in the container, the function return nullptr.
  194. * @param key Key value of the element whose mapped value is accessed.
  195. * Member type K is the keys for the elements in the container. defined in Map<K, V> as an alias of its first template parameter (Key).
  196. */
  197. const V at(const K& key) const
  198. {
  199. auto iter = _data.find(key);
  200. if (iter != _data.end())
  201. return iter->second;
  202. return nullptr;
  203. }
  204. V at(const K& key)
  205. {
  206. auto iter = _data.find(key);
  207. if (iter != _data.end())
  208. return iter->second;
  209. return nullptr;
  210. }
  211. /**
  212. * Searches the container for an element with 'key' as key and returns an iterator to it if found,
  213. * otherwise it returns an iterator to Map<K, V>::end (the element past the end of the container).
  214. *
  215. * @param key Key to be searched for.
  216. * Member type 'K' is the type of the keys for the elements in the container,
  217. * defined in Map<K, V> as an alias of its first template parameter (Key).
  218. */
  219. const_iterator find(const K& key) const
  220. {
  221. return _data.find(key);
  222. }
  223. iterator find(const K& key)
  224. {
  225. return _data.find(key);
  226. }
  227. /**
  228. * Inserts new elements in the map.
  229. *
  230. * @note If the container has already contained the key, this function will erase the old pair(key, object) and insert the new pair.
  231. * @param key The key to be inserted.
  232. * @param object The object to be inserted.
  233. */
  234. void insert(const K& key, V object)
  235. {
  236. CCASSERT(object != nullptr, "Object is nullptr!");
  237. object->retain();
  238. erase(key);
  239. _data.emplace(key, object);
  240. }
  241. /**
  242. * Removes an element with an iterator from the Map<K, V> container.
  243. *
  244. * @param position Iterator pointing to a single element to be removed from the Map<K, V>.
  245. * Member type const_iterator is a forward iterator type.
  246. */
  247. iterator erase(const_iterator position)
  248. {
  249. CCASSERT(position != _data.cend(), "Invalid iterator!");
  250. position->second->release();
  251. return _data.erase(position);
  252. }
  253. /**
  254. * Removes an element with an iterator from the Map<K, V> container.
  255. *
  256. * @param k Key of the element to be erased.
  257. * Member type 'K' is the type of the keys for the elements in the container,
  258. * defined in Map<K, V> as an alias of its first template parameter (Key).
  259. */
  260. size_t erase(const K& k)
  261. {
  262. auto iter = _data.find(k);
  263. if (iter != _data.end())
  264. {
  265. iter->second->release();
  266. _data.erase(iter);
  267. return 1;
  268. }
  269. return 0;
  270. }
  271. /**
  272. * Removes some elements with a vector which contains keys in the map.
  273. *
  274. * @param keys Keys of elements to be erased.
  275. */
  276. void erase(const std::vector<K>& keys)
  277. {
  278. for(const auto &key : keys) {
  279. this->erase(key);
  280. }
  281. }
  282. /**
  283. * All the elements in the Map<K,V> container are dropped:
  284. * their reference count will be decreased, and they are removed from the container,
  285. * leaving it with a size of 0.
  286. */
  287. void clear()
  288. {
  289. for (const auto& iter : _data)
  290. {
  291. iter.second->release();
  292. }
  293. _data.clear();
  294. }
  295. /**
  296. * Gets a random object in the map.
  297. * @return Returns the random object if the map isn't empty, otherwise it returns nullptr.
  298. */
  299. V getRandomObject() const
  300. {
  301. if (!_data.empty())
  302. {
  303. ssize_t randIdx = RandomHelper::random_int<int>(0, static_cast<int>(_data.size()) - 1);
  304. const_iterator randIter = _data.begin();
  305. std::advance(randIter , randIdx);
  306. return randIter->second;
  307. }
  308. return nullptr;
  309. }
  310. // Don't uses operator since we could not decide whether it needs 'retain'/'release'.
  311. // V& operator[] ( const K& key )
  312. // {
  313. // CCLOG("copy: [] ref");
  314. // return _data[key];
  315. // }
  316. //
  317. // V& operator[] ( K&& key )
  318. // {
  319. // CCLOG("move [] ref");
  320. // return _data[key];
  321. // }
  322. // const V& operator[] ( const K& key ) const
  323. // {
  324. // CCLOG("const copy []");
  325. // return _data.at(key);
  326. // }
  327. //
  328. // const V& operator[] ( K&& key ) const
  329. // {
  330. // CCLOG("const move []");
  331. // return _data.at(key);
  332. // }
  333. /** Copy assignment operator. */
  334. Map<K, V>& operator= ( const Map<K, V>& other )
  335. {
  336. if (this != &other) {
  337. CCLOGINFO("In the copy assignment operator of Map!");
  338. clear();
  339. _data = other._data;
  340. addRefForAllObjects();
  341. }
  342. return *this;
  343. }
  344. /** Move assignment operator. */
  345. Map<K, V>& operator= ( Map<K, V>&& other )
  346. {
  347. if (this != &other) {
  348. CCLOGINFO("In the move assignment operator of Map!");
  349. clear();
  350. _data = std::move(other._data);
  351. }
  352. return *this;
  353. }
  354. protected:
  355. /** Retains all the objects in the map */
  356. void addRefForAllObjects()
  357. {
  358. for (auto& iter : _data)
  359. {
  360. iter.second->retain();
  361. }
  362. }
  363. RefMap _data;
  364. };
  365. NS_CC_END
  366. // end group
  367. /// @}
  368. #endif /* __CCMAP_H__ */