如何删除数组元素

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++ 中数组的工作原理有了更好的理解,并且能够将这些知识应用到自己的程序中。

您可能感兴趣的其他 C++ 教程