Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. #include "pch.h"
  2. #include "DynamicArray.h"
  3. #include <exception>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. DynamicArray::DynamicArray(int capacity) : capacity{ capacity }, n{ 0 }
  9. {
  10. this->v = (TElem*)malloc(capacity * sizeof(TElem));
  11. }
  12.  
  13.  
  14. DynamicArray::~DynamicArray()
  15. {
  16. free(this->v);
  17. this->v = NULL;
  18. }
  19.  
  20. int DynamicArray::size() const
  21. {
  22. return this->n;
  23. }
  24.  
  25. TElem DynamicArray::getElement(int pos) const
  26. {
  27. return this->v[pos];
  28. }
  29.  
  30. TElem DynamicArray::setElement(int pos, TElem newElem)
  31. {
  32. int oldElem = this->v[pos];
  33. this->v[pos] = newElem;
  34.  
  35. for (int i = 0; i < this->n; ++i) {
  36. cout << v[i] << ' ';
  37. }
  38.  
  39. cout << "\n---------------\n";
  40.  
  41. return oldElem;
  42. }
  43.  
  44. void DynamicArray::addToEnd(TElem newElem)
  45. {
  46. if (n == capacity)
  47. {
  48. this->capacity *= 2;
  49. TElem* aux = (TElem*)realloc(this->v, this->capacity * sizeof(TElem));
  50. this->v = aux;
  51. }
  52.  
  53. this->v[n] = newElem;
  54. n++;
  55.  
  56. for (int i = 0; i < this->n; ++i) {
  57. cout << v[i] << ' ';
  58. }
  59.  
  60. cout << "\n---------------\n";
  61. }
  62.  
  63. void DynamicArray::addToPosition(int pos, TElem newElem)
  64. {
  65. if (n + 1 == capacity)
  66. {
  67. this->capacity *= 2;
  68. TElem* aux = (TElem*)realloc(this->v, this->capacity * sizeof(TElem));
  69. this->v = aux;
  70. }
  71.  
  72. if (pos == n) {
  73. v[pos] = newElem;
  74. ++n;
  75.  
  76. for (int i = 0; i < this->n; ++i) {
  77. cout << v[i] << ' ';
  78. }
  79.  
  80. cout << "\n---------------\n";
  81.  
  82. return;
  83.  
  84. }
  85.  
  86. // 0 1 2 3 4 5
  87. // 5 1
  88.  
  89. for (int i = n; i > pos; --i) {
  90. v[i] = v[i - 1];
  91. }
  92.  
  93. v[pos] = newElem;
  94. ++n;
  95.  
  96. for (int i = 0; i < this->n; ++i) {
  97. cout << v[i] << ' ';
  98. }
  99.  
  100. cout << "\n---------------\n";
  101. }
  102.  
  103. TElem DynamicArray::remove(int pos)
  104. {
  105. if (pos == n - 1) {
  106. --n;
  107.  
  108. for (int i = 0; i < this->n; ++i) {
  109. cout << v[i] << ' ';
  110. }
  111.  
  112. cout << "\n---------------\n";
  113.  
  114. return v[pos];
  115. }
  116.  
  117. int oldElem = v[pos];
  118.  
  119. for (int i = pos; i < n - 1; ++i) {
  120. v[i] = v[i + 1];
  121. }
  122.  
  123. --n;
  124.  
  125. for (int i = 0; i < this->n; ++i) {
  126. cout << v[i] << ' ';
  127. }
  128.  
  129. cout << "\n---------------\n";
  130.  
  131. return oldElem;
  132. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement