Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. struct Vector
  2. {
  3. int *data = nullptr;
  4. unsigned size = 0;
  5. unsigned capacity = 0;
  6.  
  7.  
  8. bool insert(int n, int data)
  9. {
  10. if (n > size && n >= 0)
  11. {
  12. return false;
  13. }
  14.  
  15. if (size == capacity) {
  16. int *temp = (int*)realloc(this->data, (capacity + capacity / 2) * sizeof(int));
  17. if (temp == nullptr)
  18. return false;
  19. this->data = temp;
  20. capacity +=capacity / 2;
  21. }
  22. for (int i = size - 1; i >= n; --i)
  23. {
  24. this->data[i + 1] = this->data[i];
  25. }
  26. this->data[n] = data;
  27. ++size;
  28. return true;
  29. }
  30.  
  31. void add(int number)
  32. {
  33. if (this->capacity == 0)
  34. {
  35. this->data = new int[5];
  36. this->capacity = 5;
  37. }
  38. else if (this->size == this->capacity)
  39. {
  40. this->capacity = this->capacity + this->capacity / 2;
  41. this->data = (int*)realloc(this->data, this->capacity * sizeof(int));
  42. }
  43. this->data[this->size] = number;
  44. ++this->size;
  45. }
  46.  
  47. void printVec()
  48. {
  49. cout << "[";
  50. for (int i = 0; i < this->size - 1; ++i)
  51. cout << this->data[i] << ", ";
  52. cout << this->data[this->size - 1] << "]\n";
  53. }
  54.  
  55. };
  56.  
  57.  
  58. //
  59. //
  60. //
  61. // int* addarr(int *a, int size, int number, int index)
  62. // {
  63. // a = (int*)realloc(a, (size + 1) * sizeof(int));
  64. // for (int i = size-1; i >= index; --i)
  65. // {
  66. // a[i + 1] = a[i];
  67. // }
  68. // a[index] = number;
  69. //
  70. // return a;
  71. // }
  72. //
  73.  
  74.  
  75. int main()
  76. {
  77. srand(time(0));
  78. int x = 11;
  79.  
  80. Vector a;
  81.  
  82. a.add(465);
  83. a.add(11);
  84.  
  85. a.insert(1, 55);
  86.  
  87. a.printVec();
  88.  
  89. cout << a.size << '\n';
  90. cout << a.capacity << '\n';
  91.  
  92. system("pause");
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement