C++ 程序,用于在数组中插入一个元素而不产生预期的输出。有什么建议么? [关闭]

问题描述 投票:0回答:1
#include <iostream>

using namespace std;

int main()
 {
int n=0;

cout<<"Enter the size of the Array: ";
cin>>n;

int a[n];

cout<<"Enter the Array: \n";
for(int i=0; i<n; i++){
    cin>>a[i];
}

cout<<"The Array is: \n";
for(int i=0; i<n; i++){
    cout<<a[i]<<"\n";
}

int x=0;
cout<<"Enter the value to be inserted: ";
cin>>x;

int k=0;
cout<<"Enter the desired Position: ";
cin>>k;

for(int i=n-1; i>=k; i--){
    a[i+1]=a[i];
};

a[k]=x;

cout<<"The new Array: \n";
for(int i=0; i<n+1; i++){
    cout<<a[i]<<"\n";
};

return 0;

 };`    

在此代码中,我使用 Dev C++,并尝试在不使用任何指针的情况下将元素插入所需位置。我期待在所需位置插入给定数字而不会弄乱其他元素的输出。我在输出中得到的是这样的:

Enter the size of the Array: 5
Enter the Array:
1
2
4
5
6
The Array is:
1
2
4
5
6
Enter the value to be inserted: 3
Enter the desired Position: 3
The new Array:
1
2
4
3
5
6 

我知道问题出在“k”的初始化或将其值分配给 x。我已经尝试将 k=0 初始化为 k=1 并将 a[k]=x 初始化为 a[k-1]=x 但我的输出的初始问题并没有消失。相反,更多的问题出现了

输入数组的大小:5 输入数组: 1个 2个 4个 5个 6个 阵列是: 1个 2个 4个 5个 6个 输入要插入的值:3 输入所需位置:3 新数组: 1个 2个 3个 5个 5个 6

我期待的输出是: 1个 2个 3个 4个 5个 6

请让我知道我做错了什么。

c++ arrays data-structures dev-c++ insertion
1个回答
0
投票

对于像这样的初学者可变长度数组

int a[n];

不是标准的 C++ 功能。而是使用标准容器

std::vector<int>
.

数组的索引也从

0
开始。如果您要求用户输入从
1
开始的位置,那么您需要在循环中使用它之前减小变量
k
的值。

并且您需要检查变量

k
的值是否在数组有效索引的
[0, n)
范围内。

这个for循环

for(int i=n-1; i>=k; i--){
    a[i+1]=a[i];
}; 

i
等于表达式
n - 1
中的
a[i+1]
时访问数组外的内存。

for循环的复合语句后的分号也是多余的,定义了一个空语句。

相反你应该写

for (int i=n-1; i > k; i-- )
{
    a[i] = a[i-1];
}
© www.soinside.com 2019 - 2024. All rights reserved.