3

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
4
  • 1
    use a loop to initialize Commented Oct 14, 2014 at 13:23
  • Yes i agree i can use loop. i was looking for any short and clean way. Commented Oct 14, 2014 at 13:24
  • Actually, your first will result in undefined behavior as you write 20 * sizeof(int) entries, which is well beyond the bounds of the array. Commented Oct 14, 2014 at 13:25
  • Ohh. so i think i should use 20, not sizeof(table). Commented Oct 14, 2014 at 13:26

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Using fill_n you can write:

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

Comments

1

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.

4 Comments

Not the same data layout though. They might actually want contiguous data.
imho, suggesting a whole different alternative should be a comment... You're not answering the question.
@leemes It is a solution to the problem stated in the question, that's why I put it as an answer. If there was a way of doing this simple with std::array that would be even better.
@JoachimPileborg The question only mentions an array. Of course, you were thinking out of the box which is good, and your advice is really good, but still, you're not answering the question. (PS. I'm not the downvoter)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.