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

c++中怎样用键盘输入一个数确定数组的大小?比如我输入一个n=5,再根据n确定数组有5个数值。... c++中怎样用键盘输入一个数确定数组的大小?
比如我输入一个n=5,再根据n确定数组有5个数值。
展开
 我来答
carea
2016-10-26 · TA获得超过459个赞
知道小有建树答主
回答量:395
采纳率:65%
帮助的人:101万
展开全部

标准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出来的未被初始化的值

璐人钇
2016-10-25 · TA获得超过1552个赞
知道小有建树答主
回答量:1365
采纳率:69%
帮助的人:649万
展开全部
用new来分配空间
追问
可以给个具体的例子吗?
追答
cin >> n;
int *a = new int[n];
......
delete [] a;
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式