How to initialize a static array to certain value

2020-04-11 10:57发布

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?

4条回答
Rolldiameter
2楼-- · 2020-04-11 11:14

You can't do this. You need an explicit for loop and a flag to avoid initializing more than once:

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];
}
查看更多
叼着烟拽天下
3楼-- · 2020-04-11 11:18

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):

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

Another option, that I actually like more is to perform the init in a 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];
}
查看更多
4楼-- · 2020-04-11 11:21

You can use fill with std::array and a IIL(immediately invoked 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;
}();
查看更多
我想做一个坏孩纸
5楼-- · 2020-04-11 11:29

You can do it for example the following way by means of introducing one more static variable

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];
}
查看更多
登录 后发表回答