简体   繁体   中英

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

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.

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM