CCVector.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /****************************************************************************
  2. Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2013-2017 Chukong Technologies
  5. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  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. #ifndef __CCVECTOR_H__
  24. #define __CCVECTOR_H__
  25. #include "base/ccMacros.h"
  26. #include "base/CCRef.h"
  27. #include <vector>
  28. #include <functional>
  29. #include <algorithm> // for std::find
  30. /**
  31. * @addtogroup base
  32. * @{
  33. */
  34. NS_CC_BEGIN
  35. /*
  36. * Similar to std::vector, but it will manage reference count automatically internally.
  37. * Which means it will invoke Ref::retain() when adding an element, and invoke Ref::release() when removing an element.
  38. * @warn The element should be `Ref` or its sub-class.
  39. * @lua NA
  40. */
  41. template<class T>
  42. class Vector
  43. {
  44. public:
  45. // ------------------------------------------
  46. // Iterators
  47. // ------------------------------------------
  48. /** Iterator, can be used to loop the Vector. */
  49. using iterator = typename std::vector<T>::iterator;
  50. /** Const iterator, can be used to loop the Vector. */
  51. using const_iterator = typename std::vector<T>::const_iterator;
  52. /** Reversed iterator, can be used to loop the Vector in reverse sequence. */
  53. using reverse_iterator = typename std::vector<T>::reverse_iterator;
  54. /** Reversed iterator, can be used to loop the Vector in reverse sequence. */
  55. using const_reverse_iterator = typename std::vector<T>::const_reverse_iterator;
  56. /** Returns an iterator pointing the first element of the Vector. */
  57. iterator begin() { return _data.begin(); }
  58. /** Returns an iterator pointing the first element of the Vector. */
  59. const_iterator begin() const { return _data.begin(); }
  60. /**
  61. * Returns an iterator referring to the `past-the-end` element in the Vector container.
  62. * The past-the-end element is the theoretical element that would follow the last element in the Vector.
  63. * It does not point to any element, and thus shall not be dereferenced.
  64. */
  65. iterator end() { return _data.end(); }
  66. /**
  67. * Returns iterator referring to the `past-the-end` element in the Vector container.
  68. * The past-the-end element is the theoretical element that would follow the last element in the Vector.
  69. * It does not point to any element, and thus shall not be dereferenced.
  70. */
  71. const_iterator end() const { return _data.end(); }
  72. /** Returns a const_iterator pointing the first element of the Vector. */
  73. const_iterator cbegin() const { return _data.cbegin(); }
  74. /** Returns a const_iterator pointing the `past-the-end` element of the Vector. */
  75. const_iterator cend() const { return _data.cend(); }
  76. /** Returns a reverse iterator pointing to the last element of the Vector. */
  77. reverse_iterator rbegin() { return _data.rbegin(); }
  78. /** Returns a reverse iterator pointing to the last element of the Vector. */
  79. const_reverse_iterator rbegin() const { return _data.rbegin(); }
  80. /** Returns a reverse iterator pointing to the theoretical element preceding the
  81. * first element of the vector (which is considered its reverse end).
  82. */
  83. reverse_iterator rend() { return _data.rend(); }
  84. /** Returns a reverse iterator pointing to the theoretical element preceding the
  85. * first element of the vector (which is considered its reverse end).
  86. */
  87. const_reverse_iterator rend() const { return _data.rend(); }
  88. /** Returns a const_reverse_iterator pointing to the last element in the container (i.e., its reverse beginning). */
  89. const_reverse_iterator crbegin() const { return _data.crbegin(); }
  90. /** Returns a const_reverse_iterator pointing to the theoretical element preceding the first element in
  91. * the container (which is considered its reverse end).
  92. */
  93. const_reverse_iterator crend() const { return _data.crend(); }
  94. /** Constructor. */
  95. Vector<T>()
  96. : _data()
  97. {
  98. static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");
  99. }
  100. /**
  101. * Constructor with a capacity.
  102. * @param capacity Capacity of the Vector.
  103. */
  104. explicit Vector<T>(ssize_t capacity)
  105. : _data()
  106. {
  107. static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");
  108. CCLOGINFO("In the default constructor with capacity of Vector.");
  109. reserve(capacity);
  110. }
  111. /** Constructor with initializer list. */
  112. Vector<T>(std::initializer_list<T> list)
  113. {
  114. for (auto& element : list)
  115. {
  116. pushBack(element);
  117. }
  118. }
  119. /** Destructor. */
  120. ~Vector<T>()
  121. {
  122. CCLOGINFO("In the destructor of Vector.");
  123. clear();
  124. }
  125. /** Copy constructor. */
  126. Vector<T>(const Vector<T>& other)
  127. {
  128. static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");
  129. CCLOGINFO("In the copy constructor!");
  130. _data = other._data;
  131. addRefForAllObjects();
  132. }
  133. /** Constructor with std::move semantic. */
  134. Vector<T>(Vector<T>&& other)
  135. {
  136. static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");
  137. CCLOGINFO("In the move constructor of Vector!");
  138. _data = std::move(other._data);
  139. }
  140. /** Copy assignment operator. */
  141. Vector<T>& operator=(const Vector<T>& other)
  142. {
  143. if (this != &other) {
  144. CCLOGINFO("In the copy assignment operator!");
  145. clear();
  146. _data = other._data;
  147. addRefForAllObjects();
  148. }
  149. return *this;
  150. }
  151. /** Copy assignment operator with std::move semantic. */
  152. Vector<T>& operator=(Vector<T>&& other)
  153. {
  154. if (this != &other) {
  155. CCLOGINFO("In the move assignment operator!");
  156. clear();
  157. _data = std::move(other._data);
  158. }
  159. return *this;
  160. }
  161. // Don't uses operator since we could not decide whether it needs 'retain'/'release'.
  162. // T& operator[](int index)
  163. // {
  164. // return _data[index];
  165. // }
  166. //
  167. // const T& operator[](int index) const
  168. // {
  169. // return _data[index];
  170. // }
  171. /**
  172. * Requests that the vector capacity be at least enough to contain n elements.
  173. * @param capacity Minimum capacity requested of the Vector.
  174. */
  175. void reserve(ssize_t n)
  176. {
  177. _data.reserve(n);
  178. }
  179. /** @brief Returns the size of the storage space currently allocated for the Vector, expressed in terms of elements.
  180. * @note This capacity is not necessarily equal to the Vector size.
  181. * It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.
  182. * @return The size of the currently allocated storage capacity in the Vector, measured in terms of the number elements it can hold.
  183. */
  184. ssize_t capacity() const
  185. {
  186. return _data.capacity();
  187. }
  188. /** @brief Returns the number of elements in the Vector.
  189. * @note This is the number of actual objects held in the Vector, which is not necessarily equal to its storage capacity.
  190. * @return The number of elements in the Vector.
  191. */
  192. ssize_t size() const
  193. {
  194. return _data.size();
  195. }
  196. /** @brief Returns whether the Vector is empty (i.e. whether its size is 0).
  197. * @note This function does not modify the container in any way. To clear the content of a vector, see Vector<T>::clear.
  198. */
  199. bool empty() const
  200. {
  201. return _data.empty();
  202. }
  203. /** Returns the maximum number of elements that the Vector can hold. */
  204. ssize_t max_size() const
  205. {
  206. return _data.max_size();
  207. }
  208. /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */
  209. ssize_t getIndex(T object) const
  210. {
  211. auto iter = std::find(_data.begin(), _data.end(), object);
  212. if (iter != _data.end())
  213. return iter - _data.begin();
  214. return -1;
  215. }
  216. /** @brief Find the object in the Vector.
  217. * @param object The object to find.
  218. * @return Returns an iterator which refers to the element that its value is equals to object.
  219. * Returns Vector::end() if not found.
  220. */
  221. const_iterator find(T object) const
  222. {
  223. return std::find(_data.begin(), _data.end(), object);
  224. }
  225. /** @brief Find the object in the Vector.
  226. * @param object The object to find.
  227. * @return Returns an iterator which refers to the element that its value is equals to object.
  228. * Returns Vector::end() if not found.
  229. */
  230. iterator find(T object)
  231. {
  232. return std::find(_data.begin(), _data.end(), object);
  233. }
  234. /** Returns the element at position 'index' in the Vector. */
  235. T at(ssize_t index) const
  236. {
  237. CCASSERT( index >= 0 && index < size(), "index out of range in getObjectAtIndex()");
  238. return _data[index];
  239. }
  240. /** Returns the first element in the Vector. */
  241. T front() const
  242. {
  243. return _data.front();
  244. }
  245. /** Returns the last element of the Vector. */
  246. T back() const
  247. {
  248. return _data.back();
  249. }
  250. /** Returns a random element of the Vector. */
  251. T getRandomObject() const
  252. {
  253. if (!_data.empty())
  254. {
  255. ssize_t randIdx = RandomHelper::random_int<int>(0, static_cast<int>(_data.size()) - 1);
  256. return *(_data.begin() + randIdx);
  257. }
  258. return nullptr;
  259. }
  260. /**
  261. * Checks whether an object is in the container.
  262. * @param object The object to be checked.
  263. * @return True if the object is in the container, false if not.
  264. */
  265. bool contains(T object) const
  266. {
  267. return( std::find(_data.begin(), _data.end(), object) != _data.end() );
  268. }
  269. /**
  270. * Checks whether two vectors are equal.
  271. * @param other The vector to be compared.
  272. * @return True if two vectors are equal, false if not.
  273. */
  274. bool equals(const Vector<T> &other) const
  275. {
  276. ssize_t s = this->size();
  277. if (s != other.size())
  278. return false;
  279. for (ssize_t i = 0; i < s; i++)
  280. {
  281. if (this->at(i) != other.at(i))
  282. {
  283. return false;
  284. }
  285. }
  286. return true;
  287. }
  288. // Adds objects
  289. /** Adds a new element at the end of the Vector. */
  290. void pushBack(T object)
  291. {
  292. CCASSERT(object != nullptr, "The object should not be nullptr");
  293. _data.push_back( object );
  294. object->retain();
  295. }
  296. /** Push all elements of an existing Vector to the end of current Vector. */
  297. void pushBack(const Vector<T>& other)
  298. {
  299. for(const auto &obj : other) {
  300. _data.push_back(obj);
  301. obj->retain();
  302. }
  303. }
  304. /**
  305. * Insert an object at certain index.
  306. * @param index The index to be inserted at.
  307. * @param object The object to be inserted.
  308. */
  309. void insert(ssize_t index, T object)
  310. {
  311. CCASSERT(index >= 0 && index <= size(), "Invalid index!");
  312. CCASSERT(object != nullptr, "The object should not be nullptr");
  313. _data.insert((std::begin(_data) + index), object);
  314. object->retain();
  315. }
  316. // Removes Objects
  317. /** Removes the last element in the Vector. */
  318. void popBack()
  319. {
  320. CCASSERT(!_data.empty(), "no objects added");
  321. auto last = _data.back();
  322. _data.pop_back();
  323. last->release();
  324. }
  325. /** Remove a certain object in Vector.
  326. * @param object The object to be removed.
  327. * @param removeAll Whether to remove all elements with the same value.
  328. * If its value is 'false', it will just erase the first occurrence.
  329. */
  330. void eraseObject(T object, bool removeAll = false)
  331. {
  332. CCASSERT(object != nullptr, "The object should not be nullptr");
  333. if (removeAll)
  334. {
  335. for (auto iter = _data.begin(); iter != _data.end();)
  336. {
  337. if ((*iter) == object)
  338. {
  339. iter = _data.erase(iter);
  340. object->release();
  341. }
  342. else
  343. {
  344. ++iter;
  345. }
  346. }
  347. }
  348. else
  349. {
  350. auto iter = std::find(_data.begin(), _data.end(), object);
  351. if (iter != _data.end())
  352. {
  353. _data.erase(iter);
  354. object->release();
  355. }
  356. }
  357. }
  358. /** @brief Removes from the vector with an iterator.
  359. * @param position Iterator pointing to a single element to be removed from the Vector.
  360. * @return An iterator pointing to the new location of the element that followed the last element erased by the function call.
  361. * This is the container end if the operation erased the last element in the sequence.
  362. */
  363. iterator erase(iterator position)
  364. {
  365. CCASSERT(position >= _data.begin() && position < _data.end(), "Invalid position!");
  366. (*position)->release();
  367. return _data.erase(position);
  368. }
  369. /** @brief Removes from the Vector with a range of elements ( [first, last) ).
  370. * @param first The beginning of the range.
  371. * @param last The end of the range, the 'last' will not be removed, it's only for indicating the end of range.
  372. * @return An iterator pointing to the new location of the element that followed the last element erased by the function call.
  373. * This is the container end if the operation erased the last element in the sequence.
  374. */
  375. iterator erase(iterator first, iterator last)
  376. {
  377. for (auto iter = first; iter != last; ++iter)
  378. {
  379. (*iter)->release();
  380. }
  381. return _data.erase(first, last);
  382. }
  383. /** @brief Removes from the Vector by index.
  384. * @param index The index of the element to be removed from the Vector.
  385. * @return An iterator pointing to the successor of Vector[index].
  386. */
  387. iterator erase(ssize_t index)
  388. {
  389. CCASSERT(!_data.empty() && index >=0 && index < size(), "Invalid index!");
  390. auto it = std::next( begin(), index );
  391. (*it)->release();
  392. return _data.erase(it);
  393. }
  394. /** @brief Removes all elements from the Vector (which are destroyed), leaving the container with a size of 0.
  395. * @note All the elements in the Vector will be released (reference count will be decreased).
  396. */
  397. void clear()
  398. {
  399. for( auto& it : _data) {
  400. it->release();
  401. }
  402. _data.clear();
  403. }
  404. // Rearranging Content
  405. /** Swap the values object1 and object2. */
  406. void swap(T object1, T object2)
  407. {
  408. ssize_t idx1 = getIndex(object1);
  409. ssize_t idx2 = getIndex(object2);
  410. CCASSERT(idx1>=0 && idx2>=0, "invalid object index");
  411. std::swap( _data[idx1], _data[idx2] );
  412. }
  413. /** Swap two elements by indexes. */
  414. void swap(ssize_t index1, ssize_t index2)
  415. {
  416. CCASSERT(index1 >=0 && index1 < size() && index2 >= 0 && index2 < size(), "Invalid indices");
  417. std::swap( _data[index1], _data[index2] );
  418. }
  419. /** Replace value at index with given object. */
  420. void replace(ssize_t index, T object)
  421. {
  422. CCASSERT(index >= 0 && index < size(), "Invalid index!");
  423. CCASSERT(object != nullptr, "The object should not be nullptr");
  424. _data[index]->release();
  425. _data[index] = object;
  426. object->retain();
  427. }
  428. /** Reverses the Vector. */
  429. void reverse()
  430. {
  431. std::reverse( std::begin(_data), std::end(_data) );
  432. }
  433. /** Requests the container to reduce its capacity to fit its size. */
  434. void shrinkToFit()
  435. {
  436. _data.shrink_to_fit();
  437. }
  438. protected:
  439. /** Retains all the objects in the vector */
  440. void addRefForAllObjects()
  441. {
  442. for(const auto &obj : _data) {
  443. obj->retain();
  444. }
  445. }
  446. std::vector<T> _data;
  447. };
  448. // end of base group
  449. /** @} */
  450. NS_CC_END
  451. #endif // __CCVECTOR_H__