我正在尝试在函数中初始化静态数组。
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中执行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];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句