如果固定尺寸,如何插入数组
How to insert into an array if its size is fixed?
我需要编写这样的程序:
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
。
相关文章:
- C++json插入数组
- 正在插入动态数组
- 如何在向量数组中插入元素?
- 将值插入到标准 c++ 数组的正确索引(升序)中
- C++ - 将元素按升序插入数组的 SEG 错误
- 插入数组时违反写访问冲突
- 在 std::map 中插入数组元素
- C++2D网格数组,从文件中读取和插入数组值
- 为什么我不能将元素插入数组中的列表?
- 如何安全地将元素插入数组C 中
- 如何通过迭代通过它插入数组范围
- 如果固定尺寸,如何插入数组
- 将项目插入数组
- C++通过 for 循环插入数组
- c++ 插入数组算法故障
- 将类插入数组会导致奇怪的访问错误
- 追加/打印/插入数组c++函数问题
- 从文本文件中读取数据并将数据插入数组
- 如何用c++在sql连接中插入数组元素
- 将元素插入数组中