如何使用用户输入变量制作二维数组?
How to make a two dimensional array with user input variables?
我正在做一个项目,到目前为止一切都运行顺利
int Get_floors()
{
cout << "Enter how many floors does the stablishment have" << endl;
int floors;
cin >> floors;
cout << "Enter how many places does each floor have" << endl;
int places;
cin >> places;
constexpr int floorsc = floors;
constexpr int placesc = places;
bool lugs[floorsc][placesc];
}
我试图用用户设置的列和行制作二维,但它要求变量floors
和places
是常量。
数组大小必须是编译时常量,但你的不是。所以这个:
bool lugs[floorsc][placesc];
实际上是一个可变长度数组,它不是标准C++的一部分。编写要constexpr
的用户输入不会计算它们以编译时间。
由于用户输入仅在运行时已知,因此您需要在运行时创建的东西,并且(内存,增长等(管理也在运行时进行。
标准库中的完美候选者是std::vector
.
简而言之,您可以拥有以下内容:
#include <vector> // std::vector
int Get_floors()
{
std::cout << "Enter how many floors does the stablishment have" << std::endl;
int floors; std::cin >> floors;
std::cout << "Enter how many places does each floor have" << std::endl;
int places; std::cin >> places;
// vector of vector bools
std::vector<std::vector<bool>> lugs(floors, std::vector<bool>(places));
return {}; // appropriate return;
}
当您了解std::vector
以及拥有std::vector
std::vector
的缺点时,您可以尝试提供一个类,它的作用类似于 2d 数组,但内部仅使用std::vector<Type>
。下面是一个在这种情况下可能会有所帮助的示例(Credits @user4581301(。
此外,您可能有兴趣阅读以下内容:
为什么vector
作为旁注,不要练习using namespce std;
而不是使用 2D 数组,您可以轻松使用 2Dvector
. 如果您必须根据动态变量(如用户输入(定义数组,这将非常容易工作。
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 创建 std::string 的二维数组的最佳做法
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 如何将二维数组作为类中的私有变量,然后在构造函数中设置它
- 用变量作为C++中二维数组的维数的问题
- 二维数组作为类的实例变量
- 为什么我可以声明一个二维数组与两个维度大小的变量,但不是新的
- c/c++:二维数组变量下标