Guest User

Untitled

a guest
Feb 22nd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include "Vector.hpp"
  2. #include <utility>
  3.  
  4. //double_capacity
  5. void Vector::double_capacity(){
  6. int *temp = new int[2*capacity];
  7. std::size_t temp_capacity = capacity * 2;
  8. //std::size_t temp_length = length * 2;
  9. for(std::size_t i=0; i < this->length; i++){
  10. temp[i] = arr[i];
  11. }
  12. delete [] arr;
  13. this->arr = temp;
  14. this->capacity = temp_capacity;
  15. //this->length = temp_length;
  16. }
  17.  
  18. //Default Constructor
  19. Vector::Vector() :
  20. arr(new int[1]),
  21. length(0),
  22. capacity(1) {}
  23.  
  24. //Copy Constructor
  25. Vector::Vector(const Vector& other) :
  26. arr(new int [other.size()]),
  27. length(other.size()),
  28. capacity(other.capacity){
  29. for (std::size_t i=0; i<other.size(); i++){
  30. this->arr[i] = other.arr[i];
  31. }
  32. }
  33.  
  34. //Move Constructor
  35. Vector::Vector(Vector&& other){
  36. arr = other.arr;
  37. length = other.length;
  38. other.arr = nullptr;
  39. other.length = 0;
  40. }
  41.  
  42. //Destructor that deallocates memory
  43. Vector::~Vector(void){
  44. delete [] arr;
  45. }
  46.  
  47. //appends a number to the end of the Vector
  48. void Vector::append(int num){
  49. if(length+1 > capacity){
  50. throw "Vector.insert: index out of bounds";
  51. double_capacity();
  52. }
  53. arr[length] = num;
  54. length++;
  55. }
  56.  
  57. //inserts a new number before the index
  58. void Vector::insert(int index, int num){
  59. if(index < 0 || index > length){
  60. throw "Vector.insert: index out of bounds";
  61. }
  62. if(this->length +1 >= this->capacity){
  63. this->double_capacity();
  64. }
  65. for(int i = this->length; i > index; --i){
  66. arr[i] = arr[i-1];
  67. }
  68. arr[index] = num;
  69. length++;
  70. }
  71.  
  72. // Removes a number at the index
  73. void Vector::remove(int index){
  74. if(index < 0 || index >= length){
  75. throw "Vector.remove: index out of bounds";
  76. }
  77. else{
  78. for (; index<length; index++)
  79. arr[index] = arr[index+1];
  80. arr[length-1] = 0;
  81. length--;
  82. }
  83. }
  84.  
  85. // Gets a number at the index
  86. int Vector::get(int index) const{
  87. if(index < 0 || index > length){
  88. throw "Vector.get: index out of bounds";
  89. }
  90. return arr[index];
  91. }
  92.  
  93. // Returns the length of the vector
  94. std::size_t Vector::size() const{
  95. return length;
  96. }
  97.  
  98. // Returns a readable/writable referece to an element
  99. // Throw a const char* if the index is out of bounds
  100. int& Vector::operator[](int index){
  101. if(index < 0 || index > length){
  102. throw "Vector.operator: index out of bounds";
  103. }
  104. int& ref = arr[index];
  105. return ref;
  106. }
Add Comment
Please, Sign In to add comment