How to remove an element from an array in C++?
In C++, arrays have a fixed length and cannot have elements directly deleted. However, specific elements can be indirectly deleted by shifting elements. Here is a method for deleting a specific element in an array.
#include <iostream>
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = 10;
int deleteValue = 5; // 要删除的元素
int i, j;
for (i = 0; i < size; i++) {
if (arr[i] == deleteValue) {
// 将后面的元素依次向前移动
for (j = i; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
size--; // 数组大小减一
}
}
// 打印删除元素后的数组
for (i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
Output:
1 2 3 4 6 7 8 9 10
In the code above, we first create an integer array called “arr” with a length of 10, then we define the element to be deleted as 5. Using two loops, the first loop iterates through the entire array, moving the following elements forward when the deletion element is found. The second loop prints the array after the deletion. The final output is the array after deleting the element 5.