C++ 数组插入元素:完整代码示例与解释
在 C++ 中,可以使用数组的插入操作来在数组中插入元素。以下是一个示例代码:
#include <iostream>
using namespace std;
void insertElement(int arr[], int size, int element, int position) {
// 检查插入位置是否有效
if (position < 0 || position > size) {
cout << 'Invalid position!' << endl;
return;
}
// 将数组元素向后移动一个位置
for (int i = size - 1; i >= position; i--) {
arr[i + 1] = arr[i];
}
// 在指定位置插入元素
arr[position] = element;
// 更新数组大小
size++;
// 输出插入后的数组
cout << 'Array after insertion: ';
for (int i = 0; i < size; i++) {
cout << arr[i] << ' ';
}
cout << endl;
}
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = 10;
int element = 99;
int position = 5;
insertElement(arr, size, element, position);
return 0;
}
在上述代码中,insertElement 函数用于在数组 arr 的指定位置 position 插入元素 element。首先,函数会检查插入位置是否有效,然后将数组元素向后移动一个位置,为新元素腾出空间。接着,将新元素插入到指定位置,并更新数组大小。最后,通过循环遍历输出插入后的数组。
注意,上述示例代码只适用于固定大小的数组。如果要在动态数组或者容器中插入元素,可以使用 vector 或者 list 等 STL 容器提供的插入函数。
原文地址: https://www.cveoy.top/t/topic/o72Z 著作权归作者所有。请勿转载和采集!