Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. #include <cstddef>
  2. #include <iostream>
  3.  
  4.  
  5. template<typename T>
  6. class Vector {
  7. private:
  8. class RawMemory {
  9. public:
  10. T * data[];
  11. RawMemory (size_t sz = 0) {
  12. data = new T[sz];
  13. }
  14. RawMemory (const RawMemory& other) {
  15. size_t i = 0;
  16. data = new T[other.size];
  17. try {
  18. for (; i < other.size; i++) {
  19. *(data[i]) = *(other.data[i]);
  20. }
  21. } catch (...) {
  22. for (int j= 0; j < i; j++) {
  23. delete data[i];
  24. delete [] data;
  25. }
  26. }
  27. }
  28. void Swap(RawMemory other) {
  29. std::swap(data, other.data);
  30. }
  31. ~RawMemory() {
  32. for (auto x : data) {
  33. delete x;
  34. }
  35. delete [] data;
  36. }
  37. };
  38. RawMemory raw;
  39. size_t siz = 0;
  40. size_t capacity = 0;
  41. public:
  42. Vector(size_t sz = 0) : siz(sz), capacity(sz), raw(sz){}
  43. Vector(const Vector& other) : siz(other.siz), capacity(other.capacity), raw(other.raw){}
  44. Vector& operator =(Vector&& other) {
  45. std::swap(siz, other.siz);
  46. std::swap(capacity, other.capacity);
  47. Swap(raw, other.raw);
  48. }
  49. Vector& operator =(const Vector& other) {
  50. auto tmp(other);
  51. (*this) = move(tmp);
  52. return *this;
  53. }
  54. size_t size() {
  55. return siz;
  56. }
  57. void pop_back() {
  58. delete raw.data[siz - 1];
  59. siz--;
  60. }
  61. void push_back(const T& elem) {
  62. if (siz == capacity) {
  63. RawMemory tmp(raw.data);
  64. for (auto i = 0; i < siz; i++) {
  65. delete raw.data[i];
  66. }
  67. delete [] raw.data;
  68. size_t oldsiz = siz;
  69. if (siz > 0) {
  70. siz *= 2;
  71. capacity *= 2;
  72. } else {
  73. siz = 1;
  74. capacity = 1;
  75. }
  76. raw.data = new T[siz];
  77. for (size_t i = 0; i < oldsiz; i++) {
  78. raw.data[i] = tmp.data[i];
  79. }
  80. }
  81. raw.data[siz] = elem;
  82. siz++;
  83. }
  84.  
  85. T& operator[](size_t ind) {
  86. return *(raw.data[ind]);
  87. }
  88. const T& operator[](size_t ind) const{
  89. return *(raw.data[ind]);
  90. }
  91. ~Vector(){}
  92. };
  93.  
  94. int main()
  95. {
  96. Vector<int> a(3);
  97. a[0] = 2;
  98. a[1] = 3;
  99. a[2] = 1;
  100. std::cout << a[0] << " " << a[1] << " " << a[2] << std::endl;
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement