이 튜토리얼에서는 두 개의 루프와 온 루프가 있는 요소를 삭제하는 방법을 배울 것입니다. 요소를 삭제할 필요가 없습니다. 삭제 요소를 다음 요소로 교체하기만 하면 됩니다.
두 개의 순회
두 개의 루프를 사용하여 배열에서 요소를 삭제하는 단계를 살펴보겠습니다.
-
배열을 초기화하고 요소를 삭제합니다.
-
요소를 삭제하는 함수를 작성하십시오.
-
배열을 반복하고 요소를 검색합니다.
-
요소를 찾으면 루프를 끊습니다.
-
요소가 발견되면 배열의 크기를 줄입니다.
-
모든 요소를 이전 색인으로 이동합니다.
-
배열의 새로운 크기를 반환합니다.
-
예시
코드를 봅시다.
#include <bits/stdc++.h>
using namespace std;
int searchAndDeleteElement(int arr[], int n, int k) {
int i;
// searching for the element
for (i = 0; i < n; i++) {
if (arr[i] == k) {
break;
}
}
// if the element is present
if (i < n) {
// moving all the elements to previous index after k
n = n - 1;
for (int j = i; j < n; j++) {
arr[j] = arr[j+1];
}
}
// returning updated index
return n;
}
int main() {
int n = 6, k = 4;
int arr[] = {1, 2, 3, 4, 5, 6};
int updatedLength = searchAndDeleteElement(arr, n, k);
// printing the array
for (int i = 0; i < updatedLength; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
1 2 3 5 6
1회 순회
하나의 루프를 사용하여 배열에서 요소를 삭제하는 단계를 살펴보겠습니다.
-
배열을 초기화하고 요소를 삭제합니다.
-
요소를 삭제하는 함수를 작성하십시오.
-
배열을 반복하고 요소를 검색합니다.
-
요소가 발견되면 해당 문을 건너뜁니다.
-
모든 요소를 이전 색인으로 이동합니다.
-
요소가 발견되면 n - 1을 반환하고 그렇지 않으면 n을 반환합니다.
-
예시
코드를 봅시다.
#include <bits/stdc++.h>
using namespace std;
int searchAndDeleteElement(int arr[], int n, int k) {
// checking for the last element
if (arr[n-1] == k) {
return n - 1;
}
bool isElementFound = false;
for (int i = 0; i < n; i++) {
// checking for k
if (arr[i] == k && !isElementFound) {
isElementFound = true;
continue;
}
// if the element is already found move all the element to their previous indexes
if (isElementFound) {
arr[i-1] = arr[i];
}
}
// returning updated n
if (isElementFound) {
return n - 1;
}
return n;
}
int main() {
int n = 6, k = 4;
int arr[] = {1, 2, 3, 4, 5, 6};
int updatedLength = searchAndDeleteElement(arr, n, k);
// printing the array
for (int i = 0; i < updatedLength; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
} 출력
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
1 2 3 5 6
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.