如果固定尺寸,如何插入数组

How to insert into an array if its size is fixed?

本文关键字:插入 数组 何插入 如果      更新时间:2023-10-16

我需要编写这样的程序:

The original elements of the array
20 34 45 2 10
Enter the index and number for insertion
3 12
Elements after insertion
20 34 45 12 2 10

我声明一个数组来存储初始数字:

int array[5] = { 20, 34, 45, 2, 10 };

但是如何插入此数组?

c 中的数组的大小固定,因此5 int的数组不能容纳5个以上的int,因为这是分配的内存量,而不再是。您可以查看其他数据结构,例如列表和向量,也可以声明您的数组足够大,可以容纳所需的所有对象。在这里,您可能需要查看链接的列表,这些列表使插入不动,而不会移动所有其他元素。

在C 词典中,'数组'是C风格的数组,那几乎不应该使用。改用std::vector,它具有数组 - 词(例如用[]索引)加上诸如insert

如果您所拥有的尺寸是固定的,则可以使用std::array

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    // vector is just as convenient as an array to initialize
    vector<int> array = { 20, 34, 45, 2, 10 };
    cout << "The original elements of the array" << endl;
    // you can use range-based for loops with containers
    for (auto val : array)
        cout << val << ' ';
    cout << endl;
    int index;
    int number;
    cout << "Enter the index and number for insertion" << endl;
    cin >> index;
    cin >> number;
    // vector support insert, and many other operations
    array.insert( array.begin()+index, number );
    cout << "Elements after insertion" << endl;
    for (auto val : array)
        cout << val << ' ';
    cout << endl;
}

我的答案发生了显着更改。

当然,您无法将其插入此固定大小数组中。

有两种方法可以做您需要的方法。

第一种方法是在需要时分配足够的内存。 std::vector成功应对此任务。

vector<int> arr { 20, 34, 45, 2, 10 };
size_t index;
int number;
// input index and number
arr.insert(arr.begin() + index, number);

第二种方法是保留足够的内存以存储任何潜在的元素。在您的情况下,只需保留一个元素以存储插入数字即可。最好使用std::array

const size_t N { 5 };
array<int, N + 1> arr { 20, 34, 45, 2, 10 };
size_t index;
int number;
// input index and number
for (size_t i = N; i > index; --i) {
    arr[i] = arr[i - 1];
}
arr[index] = number;

如果您被迫不使用C 11,请更换

const size_t N { 5 };
array<int, N + 1> arr { 20, 34, 45, 2, 10 };

to

const size_t N = 5;
int arr[N + 1] = { 20, 34, 45, 2, 10 };

请注意,此类实验室分配通常需要用户输入数据。在这种情况下,数组大小仅在运行时才知道,并且您被迫使用std::vector