可变长度数组可以具有用户所需的大小,即它们可以具有可变大小。
下面给出了在C ++中实现可变长度数组的程序-
#include <iostream> #include <string> using namespace std; int main() { int *array, size; cout<<"Enter size of array: "<<endl; cin>>size; array = new int [size]; cout<<"Enter array elements: "<<endl; for (int i = 0; i < size; i++) cin>>array[i]; cout<<"The array elements are: "; for(int i = 0; i < size; i++) cout<<array[i]<<" "; cout<<endl; delete []array; return 0; }
上面程序的输出如下-
Enter size of array: 10 Enter array elements: 11 54 7 87 90 2 56 12 36 80 The array elements are: 11 54 7 87 90 2 56 12 36 80
在上面的程序中,首先将数组初始化。然后,向用户请求数组大小和数组元素。这在下面给出-
cout<<"Enter size of array: "<<endl; cin>>size; array = new int [size]; cout<<"Enter array elements: "<<endl; for (int i = 0; i < size; i++) cin>>array[i];
最后,显示数组元素并删除该数组。这在下面给出-
cout<<"The array elements are: "; for(int i = 0; i < size; i++) cout<<array[i]<<" "; cout<<endl; delete []array;