配列要素を削除する方法

C++C++Beginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

このチュートリアルでは、C++ で特定の位置にある配列要素を削除する方法を学びます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/arrays("Arrays") cpp/ControlFlowGroup -.-> cpp/for_loop("For Loop") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/arrays -.-> lab-96146{{"配列要素を削除する方法"}} cpp/for_loop -.-> lab-96146{{"配列要素を削除する方法"}} cpp/output -.-> lab-96146{{"配列要素を削除する方法"}} cpp/user_input -.-> lab-96146{{"配列要素を削除する方法"}} cpp/files -.-> lab-96146{{"配列要素を削除する方法"}} cpp/code_formatting -.-> lab-96146{{"配列要素を削除する方法"}} end

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