c++ - 如何在 C++ 函数中将静态数组初始化为某个值?

标签 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];
}

我怎样才能做到这一点?

最佳答案

首先,我强烈建议从 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];
}

另一个我更喜欢的选项是在 lambda 中执行初始化:

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];
}

关于c++ - 如何在 C++ 函数中将静态数组初始化为某个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57232743/

相关文章:

c++ - `boost::simd::bitwise_and` 和类型兼容性

java - 多个 for 循环迭代器的最佳实践

c++ - 每个派生类的静态变量

c# - 类中的静态字段 - 是否为每个静态方法调用重新实例化?

javascript - 映射数组中的属性并在 JavaScript es6 中连接一个字符串

java - 帮助通过 JSNI 调用传递复杂对象以绕过静态范围

c++ - 如何将 boost asio 接受器限制为本地主机和/或本地网络?

c++ - 这个表达式是什么意思 : bool(__args. ..)

使用推导的 C++ 可变参数扩展

c - 从函数到主函数使用字符串