用C++定义数组大小

Jim*_*Jim 1 c++ arrays

我想将多维数组的大小定义为常量.请问最好的方法是什么?在下面的示例中,MY_CONSTANT将等于2.可以在运行时间之前确定此常量吗?

#define MY_CONSTANT <what goes here?>

std::string myArray[][3] = { 
{"test", "test", "test"},
{"test", "test", "test"}
};
Run Code Online (Sandbox Code Playgroud)

Dan*_*rey 10

您可以使用std::extent在编译时获取数组的大小:

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

const std::size_t myArraySize = std::extent<decltype(myArray)>::value;
Run Code Online (Sandbox Code Playgroud)

预处理器将无法直接定义值.你当然可以使用

#define MY_CONSTANT std::extent<decltype(myArray)>::value
Run Code Online (Sandbox Code Playgroud)

但我想这不是真的,你想要做什么.