irrArray.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. // Copyright (C) 2002-2012 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine" and the "irrXML" project.
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h and irrXML.h
  4. #ifndef IRR_ARRAY_H_INCLUDED
  5. #define IRR_ARRAY_H_INCLUDED
  6. #include "irrTypes.h"
  7. #include "heapsort.h"
  8. #include "irrAllocator.h"
  9. #include "irrMath.h"
  10. namespace irr
  11. {
  12. namespace core
  13. {
  14. //! Self reallocating template array (like stl vector) with additional features.
  15. /** Some features are: Heap sorting, binary search methods, easier debugging.
  16. */
  17. template <class T, typename TAlloc = irrAllocator<T> >
  18. class array
  19. {
  20. public:
  21. //! Default constructor for empty array.
  22. array() : data(0), allocated(0), used(0),
  23. strategy(ALLOC_STRATEGY_DOUBLE), free_when_destroyed(true), is_sorted(true)
  24. {
  25. }
  26. //! Constructs an array and allocates an initial chunk of memory.
  27. /** \param start_count Amount of elements to pre-allocate. */
  28. explicit array(u32 start_count) : data(0), allocated(0), used(0),
  29. strategy(ALLOC_STRATEGY_DOUBLE),
  30. free_when_destroyed(true), is_sorted(true)
  31. {
  32. reallocate(start_count);
  33. }
  34. //! Copy constructor
  35. array(const array<T, TAlloc>& other) : data(0)
  36. {
  37. *this = other;
  38. }
  39. //! Destructor.
  40. /** Frees allocated memory, if set_free_when_destroyed was not set to
  41. false by the user before. */
  42. ~array()
  43. {
  44. clear();
  45. }
  46. //! Reallocates the array, make it bigger or smaller.
  47. /** \param new_size New size of array.
  48. \param canShrink Specifies whether the array is reallocated even if
  49. enough space is available. Setting this flag to false can speed up
  50. array usage, but may use more memory than required by the data.
  51. */
  52. void reallocate(u32 new_size, bool canShrink=true)
  53. {
  54. if (allocated==new_size)
  55. return;
  56. if (!canShrink && (new_size < allocated))
  57. return;
  58. T* old_data = data;
  59. data = allocator.allocate(new_size); //new T[new_size];
  60. allocated = new_size;
  61. // copy old data
  62. const s32 end = used < new_size ? used : new_size;
  63. for (s32 i=0; i<end; ++i)
  64. {
  65. // data[i] = old_data[i];
  66. allocator.construct(&data[i], old_data[i]);
  67. }
  68. // destruct old data
  69. for (u32 j=0; j<used; ++j)
  70. allocator.destruct(&old_data[j]);
  71. if (allocated < used)
  72. used = allocated;
  73. allocator.deallocate(old_data); //delete [] old_data;
  74. }
  75. //! set a new allocation strategy
  76. /** if the maximum size of the array is unknown, you can define how big the
  77. allocation should happen.
  78. \param newStrategy New strategy to apply to this array. */
  79. void setAllocStrategy ( eAllocStrategy newStrategy = ALLOC_STRATEGY_DOUBLE )
  80. {
  81. strategy = newStrategy;
  82. }
  83. //! Adds an element at back of array.
  84. /** If the array is too small to add this new element it is made bigger.
  85. \param element: Element to add at the back of the array. */
  86. void push_back(const T& element)
  87. {
  88. insert(element, used);
  89. }
  90. //! Adds an element at the front of the array.
  91. /** If the array is to small to add this new element, the array is
  92. made bigger. Please note that this is slow, because the whole array
  93. needs to be copied for this.
  94. \param element Element to add at the back of the array. */
  95. void push_front(const T& element)
  96. {
  97. insert(element);
  98. }
  99. //! Insert item into array at specified position.
  100. /**
  101. \param element: Element to be inserted
  102. \param index: Where position to insert the new element. */
  103. void insert(const T& element, u32 index=0)
  104. {
  105. IRR_DEBUG_BREAK_IF(index>used) // access violation
  106. if (used + 1 > allocated)
  107. {
  108. // this doesn't work if the element is in the same
  109. // array. So we'll copy the element first to be sure
  110. // we'll get no data corruption
  111. const T e(element);
  112. // increase data block
  113. u32 newAlloc;
  114. switch ( strategy )
  115. {
  116. case ALLOC_STRATEGY_DOUBLE:
  117. newAlloc = used + 5 + (allocated < 500 ? used : used >> 2);
  118. break;
  119. default:
  120. case ALLOC_STRATEGY_SAFE:
  121. newAlloc = used + 1;
  122. break;
  123. }
  124. reallocate( newAlloc);
  125. // move array content and construct new element
  126. // first move end one up
  127. for (u32 i=used; i>index; --i)
  128. {
  129. if (i<used)
  130. allocator.destruct(&data[i]);
  131. allocator.construct(&data[i], data[i-1]); // data[i] = data[i-1];
  132. }
  133. // then add new element
  134. if (used > index)
  135. allocator.destruct(&data[index]);
  136. allocator.construct(&data[index], e); // data[index] = e;
  137. }
  138. else
  139. {
  140. // element inserted not at end
  141. if ( used > index )
  142. {
  143. // create one new element at the end
  144. allocator.construct(&data[used], data[used-1]);
  145. // move the rest of the array content
  146. for (u32 i=used-1; i>index; --i)
  147. {
  148. data[i] = data[i-1];
  149. }
  150. // insert the new element
  151. data[index] = element;
  152. }
  153. else
  154. {
  155. // insert the new element to the end
  156. allocator.construct(&data[index], element);
  157. }
  158. }
  159. // set to false as we don't know if we have the comparison operators
  160. is_sorted = false;
  161. ++used;
  162. }
  163. //! Clears the array and deletes all allocated memory.
  164. void clear()
  165. {
  166. if (free_when_destroyed)
  167. {
  168. for (u32 i=0; i<used; ++i)
  169. allocator.destruct(&data[i]);
  170. allocator.deallocate(data); // delete [] data;
  171. }
  172. data = 0;
  173. used = 0;
  174. allocated = 0;
  175. is_sorted = true;
  176. }
  177. //! Sets pointer to new array, using this as new workspace.
  178. /** Make sure that set_free_when_destroyed is used properly.
  179. \param newPointer: Pointer to new array of elements.
  180. \param size: Size of the new array.
  181. \param _is_sorted Flag which tells whether the new array is already
  182. sorted.
  183. \param _free_when_destroyed Sets whether the new memory area shall be
  184. freed by the array upon destruction, or if this will be up to the user
  185. application. */
  186. void set_pointer(T* newPointer, u32 size, bool _is_sorted=false, bool _free_when_destroyed=true)
  187. {
  188. clear();
  189. data = newPointer;
  190. allocated = size;
  191. used = size;
  192. is_sorted = _is_sorted;
  193. free_when_destroyed=_free_when_destroyed;
  194. }
  195. //! Set (copy) data from given memory block
  196. /** \param newData data to set, must have newSize elements
  197. \param newSize Amount of elements in newData
  198. \param newDataIsSorted Info if you pass sorted/unsorted data
  199. \param canShrink Specifies whether the array is reallocated even if
  200. enough space is available. Setting this flag to false can speed up
  201. array usage, but may use more memory than required by the data.
  202. */
  203. void set_data(const T* newData, u32 newSize, bool newDataIsSorted=false, bool canShrink=false)
  204. {
  205. reallocate(newSize, canShrink);
  206. set_used(newSize);
  207. for ( u32 i=0; i<newSize; ++i)
  208. {
  209. data[i] = newData[i];
  210. }
  211. is_sorted = newDataIsSorted;
  212. }
  213. //! Compare if given data block is identical to the data in our array
  214. /** Like operator ==, but without the need to create the array
  215. \param otherData Address to data against which we compare, must contain size elements
  216. \param size Amount of elements in otherData */
  217. bool equals(const T* otherData, u32 size) const
  218. {
  219. if (used != size)
  220. return false;
  221. for (u32 i=0; i<size; ++i)
  222. if (data[i] != otherData[i])
  223. return false;
  224. return true;
  225. }
  226. //! Sets if the array should delete the memory it uses upon destruction.
  227. /** Also clear and set_pointer will only delete the (original) memory
  228. area if this flag is set to true, which is also the default. The
  229. methods reallocate, set_used, push_back, push_front, insert, and erase
  230. will still try to deallocate the original memory, which might cause
  231. troubles depending on the intended use of the memory area.
  232. \param f If true, the array frees the allocated memory in its
  233. destructor, otherwise not. The default is true. */
  234. void set_free_when_destroyed(bool f)
  235. {
  236. free_when_destroyed = f;
  237. }
  238. //! Sets the size of the array and allocates new elements if necessary.
  239. /** Please note: This is only secure when using it with simple types,
  240. because no default constructor will be called for the added elements.
  241. \param usedNow Amount of elements now used. */
  242. void set_used(u32 usedNow)
  243. {
  244. if (allocated < usedNow)
  245. reallocate(usedNow);
  246. used = usedNow;
  247. }
  248. //! Assignment operator
  249. const array<T, TAlloc>& operator=(const array<T, TAlloc>& other)
  250. {
  251. if (this == &other)
  252. return *this;
  253. strategy = other.strategy;
  254. // (TODO: we could probably avoid re-allocations of data when (allocated < other.allocated)
  255. if (data)
  256. clear();
  257. used = other.used;
  258. free_when_destroyed = true;
  259. is_sorted = other.is_sorted;
  260. allocated = other.allocated;
  261. if (other.allocated == 0)
  262. {
  263. data = 0;
  264. }
  265. else
  266. {
  267. data = allocator.allocate(other.allocated); // new T[other.allocated];
  268. for (u32 i=0; i<other.used; ++i)
  269. allocator.construct(&data[i], other.data[i]); // data[i] = other.data[i];
  270. }
  271. return *this;
  272. }
  273. //! Equality operator
  274. bool operator == (const array<T, TAlloc>& other) const
  275. {
  276. return equals(other.const_pointer(), other.size());
  277. }
  278. //! Inequality operator
  279. bool operator != (const array<T, TAlloc>& other) const
  280. {
  281. return !(*this==other);
  282. }
  283. //! Direct access operator
  284. T& operator [](u32 index)
  285. {
  286. IRR_DEBUG_BREAK_IF(index>=used) // access violation
  287. return data[index];
  288. }
  289. //! Direct const access operator
  290. const T& operator [](u32 index) const
  291. {
  292. IRR_DEBUG_BREAK_IF(index>=used) // access violation
  293. return data[index];
  294. }
  295. //! Gets last element.
  296. T& getLast()
  297. {
  298. IRR_DEBUG_BREAK_IF(!used) // access violation
  299. return data[used-1];
  300. }
  301. //! Gets last element
  302. const T& getLast() const
  303. {
  304. IRR_DEBUG_BREAK_IF(!used) // access violation
  305. return data[used-1];
  306. }
  307. //! Gets a pointer to the array.
  308. /** \return Pointer to the array. */
  309. T* pointer()
  310. {
  311. return data;
  312. }
  313. //! Gets a const pointer to the array.
  314. /** \return Pointer to the array. */
  315. const T* const_pointer() const
  316. {
  317. return data;
  318. }
  319. //! Get number of occupied elements of the array.
  320. /** \return Size of elements in the array which are actually occupied. */
  321. u32 size() const
  322. {
  323. return used;
  324. }
  325. //! Get amount of memory allocated.
  326. /** \return Amount of memory allocated. The amount of bytes
  327. allocated would be allocated_size() * sizeof(ElementTypeUsed); */
  328. u32 allocated_size() const
  329. {
  330. return allocated;
  331. }
  332. //! Check if array is empty.
  333. /** \return True if the array is empty false if not. */
  334. bool empty() const
  335. {
  336. return used == 0;
  337. }
  338. //! Sorts the array using heapsort.
  339. /** There is no additional memory waste and the algorithm performs
  340. O(n*log n) in worst case. */
  341. void sort()
  342. {
  343. if (!is_sorted && used>1)
  344. heapsort(data, used);
  345. is_sorted = true;
  346. }
  347. //! Performs a binary search for an element, returns -1 if not found.
  348. /** The array will be sorted before the binary search if it is not
  349. already sorted. Caution is advised! Be careful not to call this on
  350. unsorted const arrays, or the slower method will be used.
  351. \param element Element to search for.
  352. \return Position of the searched element if it was found,
  353. otherwise -1 is returned. */
  354. s32 binary_search(const T& element)
  355. {
  356. sort();
  357. return binary_search(element, 0, used-1);
  358. }
  359. //! Performs a binary search for an element if possible, returns -1 if not found.
  360. /** This method is for const arrays and so cannot call sort(), if the array is
  361. not sorted then linear_search will be used instead. Potentially very slow!
  362. \param element Element to search for.
  363. \return Position of the searched element if it was found,
  364. otherwise -1 is returned. */
  365. s32 binary_search(const T& element) const
  366. {
  367. if (is_sorted)
  368. return binary_search(element, 0, used-1);
  369. else
  370. return linear_search(element);
  371. }
  372. //! Performs a binary search for an element, returns -1 if not found.
  373. /** \param element: Element to search for.
  374. \param left First left index
  375. \param right Last right index.
  376. \return Position of the searched element if it was found, otherwise -1
  377. is returned. */
  378. s32 binary_search(const T& element, s32 left, s32 right) const
  379. {
  380. if (!used)
  381. return -1;
  382. s32 m;
  383. do
  384. {
  385. m = (left+right)>>1;
  386. if (element < data[m])
  387. right = m - 1;
  388. else
  389. left = m + 1;
  390. } while((element < data[m] || data[m] < element) && left<=right);
  391. // this last line equals to:
  392. // " while((element != array[m]) && left<=right);"
  393. // but we only want to use the '<' operator.
  394. // the same in next line, it is "(element == array[m])"
  395. if (!(element < data[m]) && !(data[m] < element))
  396. return m;
  397. return -1;
  398. }
  399. //! Performs a binary search for an element, returns -1 if not found.
  400. //! it is used for searching a multiset
  401. /** The array will be sorted before the binary search if it is not
  402. already sorted.
  403. \param element Element to search for.
  404. \param &last return lastIndex of equal elements
  405. \return Position of the first searched element if it was found,
  406. otherwise -1 is returned. */
  407. s32 binary_search_multi(const T& element, s32 &last)
  408. {
  409. sort();
  410. s32 index = binary_search(element, 0, used-1);
  411. if ( index < 0 )
  412. return index;
  413. // The search can be somewhere in the middle of the set
  414. // look linear previous and past the index
  415. last = index;
  416. while ( index > 0 && !(element < data[index - 1]) && !(data[index - 1] < element) )
  417. {
  418. index -= 1;
  419. }
  420. // look linear up
  421. while ( last < (s32) used - 1 && !(element < data[last + 1]) && !(data[last + 1] < element) )
  422. {
  423. last += 1;
  424. }
  425. return index;
  426. }
  427. //! Finds an element by searching linearly from array start to end
  428. /** Can be slow with large arrays, try binary_search for those.
  429. Only works if corresponding operator== is implemented.
  430. \param element Element to search for.
  431. \return Position of the searched element if it was found, otherwise -1
  432. is returned. */
  433. template <class E>
  434. s32 linear_search(const E& element) const
  435. {
  436. for (u32 i=0; i<used; ++i)
  437. if (data[i] == element)
  438. return (s32)i;
  439. return -1;
  440. }
  441. //! Finds an element by searching linearly from array end to start.
  442. /** Can be slow with large arrays, try binary_search for those.
  443. Only works if corresponding operator== is implemented.
  444. \param element Element to search for.
  445. \return Position of the searched element if it was found, otherwise -1
  446. is returned. */
  447. template <class E>
  448. s32 linear_reverse_search(const E& element) const
  449. {
  450. for (s32 i=used-1; i>=0; --i)
  451. if (data[i] == element)
  452. return i;
  453. return -1;
  454. }
  455. //! Erases an element from the array.
  456. /** May be slow, because all elements following after the erased
  457. element have to be copied.
  458. \param index: Index of element to be erased. */
  459. void erase(u32 index)
  460. {
  461. IRR_DEBUG_BREAK_IF(index>=used) // access violation
  462. for (u32 i=index+1; i<used; ++i)
  463. {
  464. allocator.destruct(&data[i-1]);
  465. allocator.construct(&data[i-1], data[i]); // data[i-1] = data[i];
  466. }
  467. allocator.destruct(&data[used-1]);
  468. --used;
  469. }
  470. //! Erases some elements from the array.
  471. /** May be slow, because all elements following after the erased
  472. element have to be copied.
  473. \param index: Index of the first element to be erased.
  474. \param count: Amount of elements to be erased. */
  475. void erase(u32 index, s32 count)
  476. {
  477. if (index>=used || count<1)
  478. return;
  479. if (index+count>used)
  480. count = used-index;
  481. u32 i;
  482. for (i=index; i<index+count; ++i)
  483. allocator.destruct(&data[i]);
  484. for (i=index+count; i<used; ++i)
  485. {
  486. if (i-count >= index+count) // not already destructed before loop
  487. allocator.destruct(&data[i-count]);
  488. allocator.construct(&data[i-count], data[i]); // data[i-count] = data[i];
  489. if (i >= used-count) // those which are not overwritten
  490. allocator.destruct(&data[i]);
  491. }
  492. used-= count;
  493. }
  494. //! Sets if the array is sorted
  495. void set_sorted(bool _is_sorted)
  496. {
  497. is_sorted = _is_sorted;
  498. }
  499. //! Swap the content of this array container with the content of another array
  500. /** Afterward this object will contain the content of the other object and the other
  501. object will contain the content of this object.
  502. \param other Swap content with this object */
  503. void swap(array<T, TAlloc>& other)
  504. {
  505. core::swap(data, other.data);
  506. core::swap(allocated, other.allocated);
  507. core::swap(used, other.used);
  508. core::swap(allocator, other.allocator); // memory is still released by the same allocator used for allocation
  509. eAllocStrategy helper_strategy(strategy); // can't use core::swap with bitfields
  510. strategy = other.strategy;
  511. other.strategy = helper_strategy;
  512. bool helper_free_when_destroyed(free_when_destroyed);
  513. free_when_destroyed = other.free_when_destroyed;
  514. other.free_when_destroyed = helper_free_when_destroyed;
  515. bool helper_is_sorted(is_sorted);
  516. is_sorted = other.is_sorted;
  517. other.is_sorted = helper_is_sorted;
  518. }
  519. typedef TAlloc allocator_type;
  520. typedef T value_type;
  521. typedef u32 size_type;
  522. private:
  523. T* data;
  524. u32 allocated;
  525. u32 used;
  526. TAlloc allocator;
  527. eAllocStrategy strategy:4;
  528. bool free_when_destroyed:1;
  529. bool is_sorted:1;
  530. };
  531. } // end namespace core
  532. } // end namespace irr
  533. #endif