【问题标题】:How to make a two dimensional array with user input variables?如何使用用户输入变量制作二维数组?
【发布时间】:2020-06-29 19:57:52
【问题描述】:
我在做一个项目,到目前为止一切都很顺利
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 保持不变。
【问题讨论】:
标签:
c++
arrays
c++11
multidimensional-array
user-input
【解决方案1】:
数组大小需要是编译时常量,但你的不是。所以这个:
bool lugs[floorsc][placesc];
其实是一个变长数组,也就是not part of the standard 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::vectors 的缺点后,您可以尝试提供一个类,它的作用类似于二维数组,但在内部只使用std::vector<Type>。这是example which might be helpful in that case(致谢@user4581301)。
此外,您可能会对以下内容感兴趣:
Why isn't vector<bool> a STL container?
作为旁注,do not practice with using namespce std;
【讨论】:
-
快速警告:std::vector<bool> 可以实现将布尔值打包成位以节省空间。因此,vector<bool> 与常规的 vectors 和 gets its own documentation page 有点不同,以弥补差异。有时,最好用 char 或其他小整数创建 vector。
【解决方案2】:
您可以轻松地使用 2d vector,而不是使用 2d 数组。如果您必须根据用户输入等动态变量来定义数组,这将非常容易工作。