CCMap.h 12 KB

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