如何使用用户输入变量制作二维数组?

How to make a two dimensional array with user input variables?

本文关键字:二维数组 变量 何使用 用户 输入      更新时间:2023-10-16

我正在做一个项目,到目前为止一切都运行顺利

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];
}

我试图用用户设置的列和行制作二维,但它要求变量floorsplaces是常量。

数组大小必须是编译时常量,但你的不是。所以这个:

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::vectorstd::vector的缺点时,您可以尝试提供一个类,它的作用类似于 2d 数组,但内部仅使用std::vector<Type>。下面是一个在这种情况下可能会有所帮助的示例(Credits @user4581301(。

此外,您可能有兴趣阅读以下内容:

为什么vector不是STL容器?


作为旁注,不要练习using namespce std;

而不是使用 2D 数组,您可以轻松使用 2Dvector. 如果您必须根据动态变量(如用户输入(定义数组,这将非常容易工作。