Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class IntegerDynamicArray
  5. {
  6. public:
  7. IntegerDynamicArray()
  8. {
  9. currentSize = 0;
  10. maxSize = 10;
  11. dynamicArray = new int[maxSize];
  12. }
  13.  
  14. int add(int x);
  15. bool remove(int x);
  16. private:
  17. int* dynamicArray;
  18. int currentSize;
  19. int maxSize;
  20. };
  21.  
  22. int IntegerDynamicArray::add(int x)
  23. {
  24. if (currentSize == maxSize)
  25. {
  26. maxSize = maxSize * 2;
  27. int* tempArray = new int[maxSize];
  28. for (int i = 0; i < currentSize; i++)
  29. {
  30. tempArray[i] = dynamicArray[i];
  31. }
  32. tempArray[currentSize] = x;
  33. currentSize++;
  34. dynamicArray = tempArray;
  35. }
  36. else
  37. {
  38. dynamicArray[currentSize] = x;
  39. currentSize++;
  40. }
  41. return currentSize;
  42. }
  43.  
  44. bool IntegerDynamicArray::remove(int x)
  45. {
  46. for (int i = 0; i < currentSize; i++)
  47. {
  48. if (dynamicArray[i] == x)
  49. {
  50. //TODO need to delete the number and move all numbers "back" by one
  51. return true;
  52. }
  53. }
  54. return false;
  55. }
  56.  
  57. int main()
  58. {
  59. IntegerDynamicArray intDynArray;
  60. while (1)
  61. {
  62. char input;
  63. cout << "Enter A for add or R for remove: ";
  64. cin >> input;
  65. if (input == 'A')
  66. {
  67. cout << "Enter number to add: ";
  68. int x;
  69. cin >> x;
  70. cout << intDynArray.add(x) << endl;
  71. }
  72. else if (input == 'R')
  73. {
  74. cout << "Enter number to remove: ";
  75. int x;
  76. cin >> x;
  77. cout << intDynArray.remove(x) << endl;
  78. }
  79. }
  80. }
  81.  
  82. bool IntegerDynamicArray::remove(int x)
  83. {
  84. for (int i = 0; i < currentSize; i++)
  85. {
  86. if (dynamicArray[i] == x)
  87. {
  88. for ( ; i < currentSize - 1; i++)
  89. {
  90. // Assign the next element to current location.
  91. dynamicArray[i] = dynamicArray[i + 1];
  92. }
  93.  
  94. // Remove the last element as it has been moved to previous index.
  95. dynamicArray[currentSize - 1] = 0;
  96. currentSize = currentSize - 1;
  97.  
  98. return true;
  99. }
  100. }
  101. return false;
  102. }
  103.  
  104. bool IntegerDynamicArray::remove(int x)
  105. {
  106. for (int i = 0; i < currentSize; i++)
  107. {
  108. if (dynamicArray[i] == x)
  109. {
  110. int *newArray = new int[currentSize-1];
  111. std::copy(dynamicArray, dynamicArray+i, newArray);
  112. std::copy(dynamicArray+i+1, dynamicArray+currentSize, newArray+i);
  113. delete[] dynamicArray;
  114. dynamicArray = newArray;
  115. --currentSize;
  116. return true;
  117. }
  118. }
  119. return false;
  120. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement