c++中怎样用键盘输入一个数确定数组的大小? 比如我输入一个n=5,再根据n确定数组有5个数值。

c++中怎样用键盘输入一个数确定数组的大小?
比如我输入一个n=5,再根据n确定数组有5个数值。

标准C++版本:

#include <iostream>
#include <vector>
using namespace std;

int getArrayLength(void)
{
cout << "请输入数组长度:" << endl;
int arrayLength = 0;
cin >> arrayLength;

return arrayLength;
}

void printVector(const vector<int>& arr)
{
for (auto i = 0; i < arr.size(); ++i)
{
cout << "arrayInt[" << i << "]=" << arr[i] << endl;
}
}
int main(int , char**)
{
vector<int> arrayInt;
arrayInt.resize(getArrayLength());
printVector(arrayInt);

return 0;

}

数组的元素值为vector自动初始化成员的值(int的值为0)。

既然你对这个问题困惑,说明你不了解vector,那么下面就是“类C”的C++版,有时候这种版本也有适用的场景:

#include <iostream>
using namespace std;

int getArrayLength(void)
{
cout << "请输入数组长度:" << endl;
int arrayLength = 0;
cin >> arrayLength;

return arrayLength;
}

void printVector(const int* pArr, int arrLength)
{
for (auto i = 0; i < arrLength; ++i)
{
cout << "arrayInt[" << i << "]=" << pArr[i] << endl;
}
}
int main(int , char**)
{
int* pArrayInt = nullptr;
int length = getArrayLength();
pArrayInt = new int[length];//这里没有对数组长度做判断,请知晓
printVector(pArrayInt, length);
        delete[] pArrayInt;
return 0;

}

数组的元素为new出来的未被初始化的值

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-10-25
用new来分配空间追问

可以给个具体的例子吗?

追答

cin >> n;
int *a = new int[n];
......
delete [] a;

相似回答