I am trying to init a static array in a function.
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];
}
How can I achieve this?
You can't do this. You need an explicit for loop and a flag to avoid initializing more than once:
First of all, I strongly recommend moving from C arrays to
std::array
. If you do this you can have a function to perform the initialization (otherwise you can't, as a function cannot return C arrays):Another option, that I actually like more is to perform the init in a lambda:
You can use
fill
withstd::array
and a IIL(immediately invoked lambda) :You can do it for example the following way by means of introducing one more static variable