c++中怎样用键盘输入一个数确定数组的大小? 比如我输入一个n=5,再根据n确定数组有5个数值。
c++中怎样用键盘输入一个数确定数组的大小?比如我输入一个n=5,再根据n确定数组有5个数值。...
c++中怎样用键盘输入一个数确定数组的大小?
比如我输入一个n=5,再根据n确定数组有5个数值。 展开
比如我输入一个n=5,再根据n确定数组有5个数值。 展开
2个回答
展开全部
标准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出来的未被初始化的值
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询