介绍
在本教程中,我们将学习如何在 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++ 中数组的工作原理有了更好的理解,并且能够将这些知识应用到自己的程序中。