Guest User

Untitled

a guest
Feb 12th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. Data **values = null; // values is initialized in my insert function so it is
  2. // populated
  3. int count; // this keeps track of values' length
  4.  
  5.  
  6.  
  7. bool remove(Data * x) {
  8. Data **newArray = new Data *[count - 1];
  9.  
  10. for (int i = 0; i < count; i++) {
  11. while (x != values[i]) {
  12. newArray[i] = values[i];
  13. }
  14. count -= 1;
  15. return true;
  16. }
  17. values = newArray;
  18.  
  19. return false;
  20. }
  21.  
  22. count=3 values=[5,6,7] // initial insertion of 5, 6, 7
  23. five is a member of collection? 0
  24. count=3 values=[5,6] // removal of 0th element aka 5, but doesn't work
  25. five is a member of collection? 0
  26. count=4 values=[5,6,5] // re-insertion of 0th element (which is stored in
  27. five is a member of collection? 0 // my v0 variable)
  28.  
  29. Data** it = std::find(values, values + count, x);
  30. if (it != values + count) {
  31. std::copy(it + 1, values + count, it);
  32. --count;
  33. return true;
  34. }
  35. return false;
  36.  
  37. bool remove(Data * x)
  38. {
  39. bool found = false;
  40.  
  41. // See if x is in the array.
  42. for (int i = 0; i < count; i++) {
  43. if (x != values[i]) {
  44. found = true;
  45. break;
  46. }
  47. }
  48.  
  49. if (!found)
  50. {
  51. return false;
  52. }
  53.  
  54. // Only need to create the array if the item to be removed is present
  55. Data **newArray = new Data *[count - 1];
  56.  
  57. // Copy the content to the new array
  58. int newIndex = 0;
  59. for (int i = 0; i < count; i++)
  60. {
  61. if (x != values[i])
  62. newArray[newIndex++] = values[i];
  63. }
  64.  
  65. // Now change the pointers.
  66. delete[] values;
  67. count--;
  68. values = newArray;
  69. return true;
  70. }
Add Comment
Please, Sign In to add comment