Advertisement
Guest User

Untitled

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