我正在尝试在函数中初始化一个静态数组。
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];
}
我该如何实现这个目标?
我正在尝试在函数中初始化一个静态数组。
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];
}
static auto res = [] {}()
语法的含义吗? - deon cagadoes你不能这样做。你需要使用显式的for循环和一个标志来避免多次初始化:
最初的回答
int query(int x, int y) {
static bool initilized = false;
static int res[100][100]; // need to be initialized to -1
if (!initilized) {
initilized = true;
for (int i = 0; i != 100; ++i) {
for (int j = 0; j != 100; ++j) {
res[i][j] = -1;
}
}
}
if (res[x][y] == -1) {
res[x][y] = time_consuming_work(x, y);
}
return res[x][y];
}
int query(int x, int y) {
static bool initialized;
static int res[100][100]; // need to be initialized to -1
if ( not initialized )
{
for ( auto &row : res )
{
for ( auto &item : row ) item = -1;
}
initialized = true;
}
if (res[x][y] == -1) {
res[x][y] = time_consuming_work(x, y);
}
return res[x][y];
}
fill
和std::array
以及一个IIL(立即调用的lambda表达式):static std::array<std::array<int, 100>, 100> res = [] () {
std::array<int, 100> default_arr;
default_arr.fill(-1);
std::array<std::array<int, 100>, 100> ret;
ret.fill(default_arr);
return ret;
}();
const
变量:https://dev59.com/Y6Xja4cB1Zd3GeqPP1y0#46345224 - Robert Andrzejuk