为数组的大小声明一个单独的变量 const int 是一个好习惯吗?或者只是一个标准的 int array[n] 就足够了?

declaring a separate variable const int for the size of the arrays a good practice? or just a standard int array[n] is good enough?

我只是想知道什么是创建具有预定大小的数组的最佳实践?

const int MAXELS = 5;
int arr[MAXELS];

int arr[5];

我认为它们的用途相同,但如果有什么东西可以使另一个更好,我将使用它...

在这种情况下,我更喜欢使用 std::array,因为数组及其大小将封装在一个实例中,您可以轻松地在函数调用中携带大小值。你得到 std::array 的大小 .size().

constexpr std::size_t wantedSize = 5;           // Predetermined size (needs to be const/constexpr)
std::array<int, wantedSize> arr;

constexpr std::size_t sizeOfArray = arr.size(); // 5

对于大小可变的动态数组,我通常使用std::vector。 您可以通过使用参数调用它或使用 reserve(size_type n) 函数在 std::vector 上预分配内存。

std::vector<int> arr(wantedSize);

std::vector<int> arr;
arr.reserve(wantedSize);