我正在尝试在函数中初始化静态数组。
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/