是否可以允许用户使用键盘输入数组大小? [英] Is it possible to allow a user to enter an array size with a keyboard?

查看:134
本文介绍了是否可以允许用户使用键盘输入数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以允许用户使用键盘输入数组的大小?

Is it possible to allow the user to enter the size of an array with a keyboard?

我知道数组不能改变大小.我唯一想到的解决方案是:

I know that arrays can't change size. The only solution I could think of is this:

int userSize;

cin >> userSize;

const int SIZE = userSize;

int array[SIZE];

如何验证此方法有效?我应该改用向量吗?

How can I verify that this works? Should I use a vector instead?

推荐答案

可变长度数组 未获得C ++标准的批准. C ++ Standard要求数组的大小必须必须是编译时间常数.
您可以通过 gcc中提供的编译器扩展 使用VLA,但请注意如果这样做,则您的代码不可移植.

Variable Length Arrays are not approved by C++ standard. C++ Standard mandates that the size of an array must be an compile time constant.
You can use VLA's through compiler extension provided in gcc but note the your code is not portable if you do so.

批准的标准方法是使用 std :: vector

Standard approved way of doing this is to use std::vector.

这篇关于是否可以允许用户使用键盘输入数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆