如何在C ++中的函数中将静态数组初始化为特定值?

Leo*_*eng 3 c++ arrays static initialization

我正在尝试在函数中初始化静态数组。

int query(int x, int y) {
    static int res[100][100]; // need to be initialized to -1
    if (res[x][y] == -1) {
        res[x][y] = time_consuming_work(x, y);
    }
    return res[x][y];
}
Run Code Online (Sandbox Code Playgroud)

我该如何实现?

bol*_*lov 7

首先,我强烈建议您从C数组移至std::array。如果执行此操作,则可以有一个函数来执行初始化(否则就不能,因为函数不能返回C数组):

constexpr std::array<std::array<int, 100>, 100> init_query_array()
{
    std::array<std::array<int, 100>, 100> r{};
    for (auto& line : r)
        for (auto& e : line)
            e = -1;
    return r;
}

int query(int x, int y) {
    static std::array<std::array<int, 100>, 100> res = init_query_array();

    if (res[x][y] == -1) {
        res[x][y] = time_consuming_work(x, y);
    }
    return res[x][y];
}
Run Code Online (Sandbox Code Playgroud)

我实际上更喜欢的另一个选择是在lambda中执行init:

int query(int x, int y) {
    static auto res = [] {
        std::array<std::array<int, 100>, 100> r;
        for (auto& line : r)
            for (auto& e : line)
                e = -1;
        return r;
    }();

    if (res[x][y] == -1) {
        res[x][y] = time_consuming_work(x, y);
    }
    return res[x][y];
}
Run Code Online (Sandbox Code Playgroud)