我试着写这段代码,但它说表达式的计算结果不是常数。我了解到这是因为VS不允许使用未声明的数组,因为VS不理解"n"。如何使用已声明的数组修复此代码?
#include<iostream>
using namespace std;
int main()
{
int i, n;
cout << "Enter size of array:";
cin >> n;
int a[n];
cout << "Enter elements of array:" << endl;
for (i = 0; i < n; i++)
cin >> a[(i + n - 1) % n];
cout << "Result after left shift:" << endl;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
如何使用声明的数组修复此代码?
选项1
声明大小足够大的数组,并确保n
小于或等于使用数组之前的大小。
int i, n;
int a[1000];
cout << "Enter size of array (less than or equal to 1000):";
cin >> n;
if ( n > 1000 )
{
// Deal with the problem.
}
else
{
// Use the array.
}
选项2
使用std::vector
。
int i, n;
cout << "Enter size of array:";
cin >> n;
std::vector<int> a(n);
可变长度数组(VLA(不是C++语言的一部分,尽管一些编译器(如g++(支持将其作为扩展。
您应该使用标准模板库中的std::vector
容器。一旦声明并正确初始化,std::vector
就可以像普通数组一样使用:
#include<iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;
int main()
{
int i, n;
cout << "Enter size of array:";
cin >> n;
std::vector<int> a(n);
cout << "Enter elements of array:" << endl;
for (i = 0; i < n; i++)
cin >> a[(i + n - 1) % n];
cout << "Result after left shift:" << endl;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
您必须在堆上分配数组,如下所示:
int* a = new int[n];
但是,当您进行堆分配时,请始终记住在使用完分配的内存后delete
:
delete[] a;
如果您不想担心删除内存,可以查看std::vector
。