Advertisement
Guest User

Untitled

a guest
Feb 18th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #include <cmath>
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <cassert>
  5.  
  6. using namespace std;
  7.  
  8. class Vector {
  9. public:
  10. int my_size;
  11. int my_capacity;
  12. int* buffer;
  13. Vector() {
  14. my_capacity = 0;
  15. my_size = 0;
  16. buffer = 0;
  17. }
  18.  
  19. Vector(const Vector & v) {
  20. my_size = v.my_size;
  21. my_capacity = v.my_capacity;
  22. buffer = new int[my_size];
  23. for (int i = 0; i < my_size; i++)
  24. buffer[i] = v.buffer[i];
  25. }
  26.  
  27. Vector(unsigned int size) {
  28. my_capacity = size;
  29. my_size = size;
  30. buffer = new int[size];
  31. }
  32.  
  33. Vector(unsigned int size, const int& initial) {
  34. my_size;
  35. my_capacity = size;
  36. buffer = new int[size];
  37. for (int i = 0; i < size; i++)
  38. buffer[i] = initial;
  39. }
  40.  
  41. int & operator[](int index) {
  42. return buffer[index];
  43. }
  44.  
  45. Vector& operator = (const Vector & v) {
  46. delete[] buffer;
  47. my_size = v.my_size;
  48. my_capacity = v.my_capacity;
  49. buffer = new int[my_size];
  50. for (int i = 0; i < my_size; i++)
  51. buffer[i] = v.buffer[i];
  52. return *this;
  53. }
  54.  
  55. void reserve(int capacity) {
  56. if (buffer == 0) {
  57. my_size = 0;
  58. my_capacity = 0;
  59. }
  60. if (capacity <= my_capacity)
  61. return;
  62. int* new_buffer = new int[capacity];
  63. assert(new_buffer);
  64. copy(buffer, buffer + my_size, new_buffer);
  65. my_capacity = capacity;
  66. delete[] buffer;
  67. buffer = new_buffer;
  68. }
  69.  
  70. void push_back(const int & v) {
  71. if (my_size >= my_capacity) {
  72. float k = (1 + sqrt(5) / 2);
  73. reserve(static_cast <int>(k * (my_size + 1)));
  74. }
  75. buffer[my_size++] = v;
  76. }
  77.  
  78. void pop_back() {
  79. my_size--;
  80. }
  81.  
  82. int size() const {
  83. return my_size;
  84. }
  85.  
  86. ~Vector() {
  87. delete[] buffer;
  88. }
  89. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement