How to initialize 2D array with the same values ​​in C ++

We can use the fill_n function to initialize a 1D array with a value.

int table[20];
fill_n(table, 20, 100);

      

But how can we initialize a 2D array with the same values.

int table[20][20];
fill_n(table, sizeof(table), 100); //this gives error

      

+3


source to share


3 answers


Using fill_n you can write:



std::fill_n(&table[0][0], sizeof(table) / sizeof(**table), 100);

      

+2


source


You can use a pointer to the first element and a pointer to one of the last:



int table[20][20];
int* begin = &table[0][0];
size_t size = sizeof(table) / sizeof(table[0][0]);
fill(begin, begin + size, 100);

      

+6


source


Use std::vector

:

std::vector<std::vector<int>> table(20, std::vector<int>(20, 100));

      

Everything is done and "filled" in the ad. No more code needed.

-1


source







All Articles