Hai lần duyệt
Duyệt lần 1 tìm vị trí phần tử cần xóa, duyệt lần 2 dịch chuyển các phần tử phía sau.
int ele = 6;
int arr[] = {11, 15, 6, 8, 9, 10};
int length = sizeof(arr)/sizeof(arr[0]);
int i;
for (i = 0; i < length; i++)
if (arr[i] == ele) break;
if (i < length) {
length--;
for (int j = i; j < length; j++)
arr[j] = arr[j+1];
}
Một lần duyệt
Sử dụng biến pos lưu vị trí tìm thấy, dịch chuyển ngay trong vòng lặp duy nhất.
int ele = 6;
int arr[] = {11, 15, 6, 8, 9, 10};
int length = sizeof(arr)/sizeof(arr[0]);
bool found = false;
int pos = -1;
for (int i = 0; i < length; i++) {
if (pos != -1) {
arr[pos] = arr[pos+1];
pos++;
}
else if (arr[i] == ele) {
pos = i;
found = true;
}
}
if (found) length--;
Ví dụ hoàn chỉnh (một lần duyệt)
#include <iostream>
using namespace std;
int main() {
int arr[] = {11, 15, 6, 8, 9, 10};
int length = sizeof(arr)/sizeof(arr[0]);
int ele = 6;
bool found = false;
int pos = -1;
for (int i = 0; i < length; i++) {
if (pos != -1) {
arr[pos] = arr[pos+1];
pos++;
}
else if (arr[i] == ele) {
pos = i;
found = true;
}
}
if (found) length--;
cout << "Mảng sau xóa: ";
for (int i = 0; i < length; i++)
cout << arr[i] << " ";
return 0;
}
Kết quả
Mảng sau xóa: 11 15 8 9 10