Junior — Middle
How can you efficiently remove an element from an array without using STL standard libraries?
sobes.tech AI
Answer from AI
To remove an element from an array without using standard STL libraries, you can do the following:
- Find the index of the element to be removed.
- Shift all elements after this index one position to the left.
- Decrease the size of the array (if the size is stored separately).
Example in C++:
void removeElement(int* arr, int& size, int value) {
int i = 0;
// Find the index of the element
while (i < size && arr[i] != value) {
++i;
}
if (i == size) return; // element not found
// Shift elements to the left
for (int j = i; j < size - 1; ++j) {
arr[j] = arr[j + 1];
}
--size; // decrease the array size
}
Here, size is the current size of the array, which should be adjusted after deletion.