array.hpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #pragma once
  2. #include <vector>
  3. namespace ylib
  4. {
  5. template<typename T>
  6. struct nolock_array
  7. {
  8. nolock_array() {
  9. m_array = nullptr;
  10. m_count = 0;
  11. }
  12. ~nolock_array(){
  13. free();
  14. }
  15. void free(){
  16. if(m_array != nullptr)
  17. delete[] m_array;
  18. m_array = nullptr;
  19. m_count = 0;
  20. }
  21. void init(const std::vector<T>& value){
  22. if(value.size() == 0)
  23. return;
  24. m_array = new T[value.size()];
  25. m_count = value.size();
  26. for(size_t i=0;i<value.size();i++){
  27. m_array[i] = value[i];
  28. }
  29. }
  30. size_t append(const T& value){
  31. std::vector<T> v;
  32. v.resize(m_count+1);
  33. for(size_t i=0;i<m_count;i++){
  34. v[i] = m_array[i];
  35. }
  36. v[m_count] = value;
  37. free();
  38. init(v);
  39. return m_count-1;
  40. }
  41. inline T get(size_t index){
  42. if(index >= m_count){
  43. printf("Unlocked array index is too long");
  44. abort();
  45. }
  46. return m_array[index];
  47. }
  48. inline size_t size() { return m_count; }
  49. T* m_array;
  50. size_t m_count;
  51. };
  52. }