how to set or initialize default value for all elements of a table or 2d array or multdimentional array

后端 未结 4 910
北恋
北恋 2020-12-11 05:18

I want to set a default nonzero value for all elements of a table or 2d array. array[size]={12} sets first elements only 12 and others are all 0 in a row.But fill(array,arra

4条回答
  •  独厮守ぢ
    2020-12-11 05:55

    This is not much better than memset, but at least you can specify the value for each int instead of each byte with std::fill used like that:

    #include 
    #include 
    
    int main() {
       int arra[10][10];
       std::fill((int*)arra,(int*)arra+sizeof(arra)/sizeof(int),45);
    
       for (auto& row : arra) {
         for (auto& x : row)
           printf("%d ", x);
         puts("");
       }
    
       return 0;
    }
    

    This relies on the array elements being contiguous in memory.

    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    45 45 45 45 45 45 45 45 45 45 
    

提交回复
热议问题