How to initialize a static array to certain value in a function in c++?

后端 未结 4 678
傲寒
傲寒 2021-01-20 20:50

I am trying to init a static array in a function.

int query(int x, int y) {
    static int res[100][100]; // need to          


        
4条回答
  •  囚心锁ツ
    2021-01-20 21:33

    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, 100> init_query_array()
    {
        std::array, 100> r{};
        for (auto& line : r)
            for (auto& e : line)
                e = -1;
        return r;
    }
    
    int query(int x, int y) {
        static std::array, 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, 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];
    }
    

提交回复
热议问题