0

Suppose that I have: unsigned char my2darray[A][B];

Is it possible to use std::fill to set all values of the 2d array to a non-0 value?

I know a vector can be used but this is performance critical code and I can't afford dynamic allocations. Unfortunately, no C++11 is allowed.

Currently used in the code is memset(my2darray, 0x12, sizeof(my2darray)); but I want to replace all memset with std::fill if possible, as the type of the array could become a class in future.

Answers which work for any type, not just chars, appreciated.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91

2 Answers2

4

Yes, because a 2d array is still a sequence of elements that are allocated as a contiguous block of memory.

    std::fill (
      &my2darray[0][0],
      &my2darray[0][0] + sizeof(my2darray) / sizeof(my2darray[0][0]),
      none_zero_value);
Eric Z
  • 14,327
  • 7
  • 45
  • 69
  • @WhozCraig It looks the same as the answer in http://stackoverflow.com/questions/3948290/whats-the-safe-way-to-fill-multidimensional-array-using-stdfill – Neil Kirk Aug 06 '14 at 10:55
  • @NeilKirk the linked answer is `char`.`sizeof()` works in that example. I should be `&my2darray[0][0]+ A*B` for this question, or `sizeof(my2darray)/sizeof(my2darray[0][0]), the choice is yours. I prefer the former in case `my2darray` is actually `Type (*)[B]` instead of fixed. – WhozCraig Aug 06 '14 at 10:56
  • @WhozCraig I think it should be a division;) – Eric Z Aug 06 '14 at 11:05
  • @EricZ division works correctly when the array is fixed. It will not when the array is only available via row-pointer, thus why I prefer the simpler math, which works in both cases. – WhozCraig Aug 06 '14 at 11:08
  • @WhozCraig If `my2darray` is a raw pointer, `&my2darray[0][0]` is a syntax error. – Eric Z Aug 06 '14 at 11:12
  • @EricZ Who said anything about a *raw* pointer? See my comment. I said `Type (*)[B]`; a **row** pointer. – WhozCraig Aug 06 '14 at 11:12
  • @WhozCraig `my2darray` is an array not a row pointer. It just decays to it in some cases. – Eric Z Aug 06 '14 at 11:27
  • @EricZ exactly. It is those "some cases" where `sizeof()` division will *not* work, but row*col will. Ex: pass the array to a function where the formal parameter is `Type (*arr)[B]`. – WhozCraig Aug 06 '14 at 11:29
  • @WhozCraig Sure, that's true. – Eric Z Aug 06 '14 at 12:21
4

If std::fill_n is an option for you and you don't want to handle sizeof operations on your array, you could use the following:

std::fill_n(*my2darray,A*B,my_val)
MatthiasB
  • 1,759
  • 8
  • 18