[我最近更换了C ++编译器,并且遇到了一个奇怪的错误,该错误是ISO C ++禁止使用可变长度数组。我清楚地记得以前的编译器未遇到此错误。这是我编写的代码片段,目的是检查此新编译器的可靠性。
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
In function 'int main()':
test.cpp:8:9: error: ISO C++ forbids variable length array 'a' [-Wvla]
int a[n]={0};
即使您看到用户以'n'作为输入,编译器也会指出该数组具有可变长度。也欢迎提供有关其他编译器版本的建议!
用std::vector
替换VLA:
#include <iostream>
#include <vector>
int main()
{
int n;
std::cin>>n;
std::vector<int> a(n);
for(int i=0;i<n;i++)
std::cin>>a[i];
for(int i=0;i<n;i++)
std::cout<<a[i]<<" ";
}
该代码在标准C ++中无效。根据C ++标准,数组大小必须是一个常量表达式。在C ++中不允许使用可变长度数组,因为C ++为此提供了std :: vector。 C标准允许VLA(可变长度数组),而C ++不允许。
您的新编译器是正确的:标准C++
中允许not可变长度数组! (GNU g++
允许它们作为扩展)。
您应该修改代码以使用std::vector
类型,而不是:
#include <iostream>
#include <vector> // Definitions for the std::vector types
//using namespace std; // This can cause problems - better only "using" specifics:
using std::cin;
using std::cout;
int main()
{
int n;
cin>>n;
// int a[n]; // Forbidden in standard C++
std::vector<int> a; // Declare "a" as a (variable-size) vector...
a.resize(n); // ...and allocate required size.
for(int i=0;i<n;i++)
cin>>a[i]; // You can still use the "[i]" syntax to access the elements
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
随时要求进一步的澄清和/或解释。