2

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.

4

2 Answers 2

3

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::vectors, 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;

Sign up to request clarification or add additional context in comments.

1 Comment

Quick caveat: std::vector<bool> can be implemented to pack the bools into bits to save space. As a result vector<bool> is a bit different from regular vectors and gets its own documentation page to cover the differences. Sometimes it's better to make a vector out of a char or other small integer instead.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.