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

后端 未结 4 776
傲寒
傲寒 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:35

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

提交回复
热议问题