C++程序来实现可变长数组
可变长数组可以根据用户需要的大小,即它们可以有可变的大小。
以下是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;
广告