简体   繁体   中英

Defining Array Size in C++

I would like to define the size of a multidimensional array as a constant. What would be the best way to do this please? In the example below, MY_CONSTANT would be equal to 2. Can this constant be determined before run time?

#define MY_CONSTANT <what goes here?>

std::string myArray[][3] = { 
{"test", "test", "test"},
{"test", "test", "test"}
};

You might use std::extent to get the size of the array at compile time:

std::string myArray[][3] = { 
  {"test", "test", "test"},
  {"test", "test", "test"}
};

const std::size_t myArraySize = std::extent<decltype(myArray)>::value;

The preprocessor will not be able to define the value directly. Of course you could use

#define MY_CONSTANT std::extent<decltype(myArray)>::value

but I guess that's not really what you want to do.

In C++11, you can use a constexpr function to initialise a compile-time constant:

template <typename T, size_t N> 
constexpr size_t array_size(T(&)[N]) {return N;}

constexpr size_t MY_CONSTANT = array_size(myArray);

(or use std::extent as another answer suggests; I didn't know about that).

Historically, you would need to initialise it with a constant expression like

const size_t MY_CONSTANT = sizeof(myArray) / sizeof(myArray[0]);

you are using C++, better use const instead of #define .

#define is a preprocessor directive which will perform textual substitution before compilation.

const int create a read only variable. so better use something like: const size_t arraySize = 2;

"Can this constant be determined before run time?"

you would have to use dynamically allocated arrays using new or better use vector from STL

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