How to initialize a 2D array with all values same?

后端 未结 6 1742
独厮守ぢ
独厮守ぢ 2021-01-29 10:49

I want to initialize a 2D array with -1 as all the value. I used memset() for this.

#include 
using namespace std;

int dp[100]         


        
6条回答
  •  忘掉有多难
    2021-01-29 11:20

    In practice, in this case, it is possible to write an helping templated function, itself based on simple for-range loops.

    One advantage is that is will work for other types of 2D arrays.

    #include    
    
    template 
    void init2d (T2d &arr, T val) {
        for (auto& row: arr) {
            for (auto& i: row) {
                i = val;
            }
        }       
    }
    
    int main() {
        const int  n = 5, m = 6;
        int a[n][m];
    
        init2d (a, -1);
        std::cout << a[n-1][m-1] << "\n";
    }
    

    If you want to initialize before main, the simplest way is to rely on STL, e.g. on std::vector or std::array, like this, for a 5x6 matrix:

    std::vector> b(5, std::vector (6, -1));
    

提交回复
热议问题