irrArray.h 15 KB

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