
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
If the order of the array doesn't matter, copy the last index to the index you want removed then resize the whole array to be one smaller.
Well this works if you have ONE AND ONLY ONE element to erase. In that case
1) if the element is one generic in the middle, you copy the last in its position and then resize the array one index shorter,
2) if the element to remove is the very last, well, you copy it into itself and then you remove it resizing.
But what if there are more elements to remove and the last element is one of them?
Let's suppose I have a generic 7 elements array
and I decide I have to remove e3 and e6.
If you call
Erase(MyArray, 3);
first you copy e6 in e3, then you resize the array, so you have this
and now if you call
Erase(MyArray, 6);
well you try to copy last element e5 in index 6 and I'm pretty sure your code is about to crash against a NullPointer wall.
It's not simply about copying last element into the one you want to remove, but you have to search ascending for to-remove elements, and descending for not-to-remove elements, making a copy one by one until the two searches cross each other.
Some code is worthing a thousand words:
About the example above, you start your search from left so you first move index l from 0 to 3
then you find that 3 is to remove but 6 too, so you move index r back to 5
and now 3 is to remove, but 5 is not, so you can finally copy e5 in 3 and move both indexes
now l < r is not verified, so it exits the while loop and you can cut the array, resizing it as its size (7) less the number of indexes you wanted to remove (2).
And that's it. Try the code with alternative toRemove array combinations and tell me if it works fine.
In alternative, I'm going to propose a solution analogue to the one in comment above using ArrayFree and ArrayCopy:
Hope this helps.
Let me know if something's wrong or you have better solutions.
Not null pointer but array exceeded. Invalid call 6, there are only 6 elements in the array at that point.