배열 요소 삭제 방법

C++Beginner
지금 연습하기

소개

이 튜토리얼에서는 C++ 에서 특정 위치의 배열 요소를 삭제하는 방법을 배우겠습니다.

새 C++ 파일 생성

~/project 디렉토리에 main.cpp라는 새로운 C++ 파일을 생성하는 것으로 시작해 보겠습니다.

cd ~/project
touch main.cpp

코드 작성

다음 코드를 복사하여 main.cpp 파일에 붙여넣으세요.

#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "Enter the size of the array: ";
    cin >> n;

    int arr[n], i, pos;

    cout << "Enter the " << n << " elements of the array: " << endl;
    for(i = 0; i < n; i++)
    {
        cin >> arr[i];
    }

    //Printing the original array before deletion
    cout << "\nThe " << n << " elements of the array, before deletion are: " << endl;
    for(i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }

    cout << "\nEnter the position, between 1 and " << n << " , of the element to be deleted: ";
    cin >> pos;

    //Performing the deletion logic
    --pos;
    for(i = pos; i <= 9; i++)
    {
        arr[i] = arr[i + 1];
    }

    cout << "\nThe " << n - 1 << " elements of the array, after deletion are: " << endl;
    for(i = 0; i < n - 1; i++)
    {
        cout << arr[i] << " ";
    }

    return 0;
}

코드 컴파일 및 실행

터미널에서 다음 명령을 실행하여 코드를 컴파일하고 실행합니다.

g++ main.cpp -o main && ./main

요약

이 튜토리얼에서는 C++ 에서 특정 위치의 배열 요소를 삭제하는 방법을 배웠습니다. 위에 설명된 단계를 따르면 C++ 에서 배열이 어떻게 작동하는지에 대한 더 나은 이해를 얻을 수 있으며, 이 지식을 자신의 프로그램에 적용할 수 있습니다.