Reputation: 21
I was working in a project, and everything was running smoothly up to this point
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];
}
I was trying to make a two dimensional with user-set columns and rows, but it asks for the variable floors
and places
to be constant.
Upvotes: 2
Views: 709
Reputation: 403
instead of using a 2d array, you can easily use a 2d vector
. it will be pretty easy to work if you have to define your arrays based on dynamic variables like user inputs.
Upvotes: 0
Reputation: 32722
Array sizes need to be compile-time constants, but yours are not. So this:
bool lugs[floorsc][placesc];
is really a variable-length array, which is not part of the standard C++. Writing the user inputs to be constexpr
will not evaluate them to compile time.
Since the user inputs are only known at run time, you need something which will be created at run time and (memory, growth, etc) managements happen also at run time.
The perfect candidate for this from the standard library is std::vector
.
In short, you could have the following:
#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;
}
When you have understood about std::vector
and the draw backs of having std::vector
of std::vector
s, you could try to provide a class, which acts like a 2d array but internally just uses std::vector<Type>
. Here is an example which might be helpful in that case (Credits @user4581301).
Also, you might be interesting to have a read on the following:
Why isn't vector<bool> a STL container?
As a side note, do not practice with using namespce std;
Upvotes: 3