在 C++ 中使用依赖于函数的大小初始化数组

Initialize array with function-depending size in C++

我正在编写一个程序来创建花名册。每个月都有不同的轮班次数,这是由一个函数决定的。在程序开始时,用户输入月份,在函数中计算相应的班次数,然后我想创建一个具有该大小的二维数组。但是显然我不能像这样初始化一个数组。谁能帮我吗?

你可能已经注意到了,我是一个非常缺乏经验的初学者,所以我很抱歉没有提前完美地表达自己。

//function to calculate number of shifts
const int getShift(const int month, const int year) {
    ...
    return x;
}

int main(){
int array[getShift(8,2019)[2];
}

我得到了类似 "expression did not evaluate to a constant" 的错误,尽管这个数字实际上是一个常数,或者至少我希望它是一个...

在此先感谢您的帮助!

必须使用说明符 constexpr 声明函数,从而满足 constexpr 函数的要求..

这是一个演示程序

#include <iostream>

constexpr int getShift( int x, int y )
{
    return y / x;
}

int main()
{
    int array[getShift(8,2019)][2];

    std::cout << sizeof( array ) / sizeof( *array ) << '\n';
}

它的输出是

252

这是对 constexpr 函数体 (C++20) 的要求列表

(3.4) — its function-body shall not enclose (Clause 8)

(3.4.1) — an asm-definition,

(3.4.2) — a goto statement,

(3.4.3) — an identifier label (8.1),

(3.4.4) — a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed.

当您需要具有动态大小的数组时,C++ 中的最佳解决方案几乎总是使用向量。

#include <array>
#include <vector>

//function to calculate number of shifts
int getShift(int month, int year) {
    ...
    return x;
}

int main() {
    std::vector<std::array<int, 2>> array(getShift(8,2019));
}

由于您需要一个二维数组,并且由于常规数组不能是向量的成员,因此我还使用了 std::array<int, 2> 作为第二维。

现在您可以像使用常规二维数组一样使用 array,特别是您可以使用 array[i][j] 访问二维数组的各个元素。