Reputation: 9212
WE can use fill_n function to initialize 1D array with value.
int table[20];
fill_n(table, 20, 100);
But how can we initialize 2D array with same values.
int table[20][20];
fill_n(table, sizeof(table), 100); //this gives error
Upvotes: 3
Views: 2912
Reputation: 18902
Using fill_n you can write:
std::fill_n(&table[0][0], sizeof(table) / sizeof(**table), 100);
Upvotes: 2
Reputation: 409176
Use std::vector
:
std::vector<std::vector<int>> table(20, std::vector<int>(20, 100));
All done and "filled" at the declaration. No more code needed.
Upvotes: 1
Reputation: 227418
You can use a pointer to the first element and a pointer to one past the last one:
int table[20][20];
int* begin = &table[0][0];
size_t size = sizeof(table) / sizeof(table[0][0]);
fill(begin, begin + size, 100);
Upvotes: 6