配列要素を削除する方法

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++ における配列の仕組みをより深く理解し、この知識を自分自身のプログラムに適用できるようになりました。