使用new分配变长数组
#include <iostream.h>
void main()
{
int len;
cout << "请输入数组的长度: ";
cin >> len;
int *array=new int[len];
cout << "数组的长度是" << len << endl;
//................
delete[] array;
return;
}
void main()
{
int len;
cout << "请输入数组的长度: ";
cin >> len;
int *array=new int[len];
cout << "数组的长度是" << len << endl;
//................
delete[] array;
return;
}
---------------------------------------------------
使用vector分配变长数组
#include <iostream>
#include <vector>
using namespace std;
void main()
{
int len;
cout << "请输入数组的长度: ";
cin >> len;
vector <int> array(len);//声明变长数组
for(int i=0;i <len;i++)
{
array[i]=i;
cout <<array[i] << "/t ";
}
return;
}
#include <vector>
using namespace std;
void main()
{
int len;
cout << "请输入数组的长度: ";
cin >> len;
vector <int> array(len);//声明变长数组
for(int i=0;i <len;i++)
{
array[i]=i;
cout <<array[i] << "/t ";
}
return;
}
本文提供了一个使用C++ new关键字手动分配变长数组的例子,并展示了如何利用C++ STL中的vector来实现变长数组的功能。通过这两个例子,读者可以了解不同方式下变长数组的内存管理及使用。
892

被折叠的 条评论
为什么被折叠?



