0

I want to initialize double 2nd array elements as -1 or 0 easily.

In case of integer, we can write like below

int cache[100][100];
memset(cache, -1, 100*100*sizeof(int));

But In case of double, How can I initialize this 2nd array easily? the best approach that I can handle, but quite ugly, is below

double cache[100][100];
for(int i=0; i<100; i++)
   for(int j=0; j<100; j++)
       cache[i][j] = -1;

Does anybody know best solution about this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Daniel kim
  • 158
  • 1
  • 13
  • 2
    Are you sure the integer version does what you expect? `memset` fills a memory area with a consistent byte, not an int. Version 2 is a much clearer indication of what you actually want to achieve. – John3136 Jul 15 '16 at 06:01
  • version 1 implies two's complement – phuclv Jul 15 '16 at 06:11
  • I know what you mean. Therefore, 'memset' can fill a memory area -1 or 0. What I want to know is that there is a certain STL that can achieve above goal. – Daniel kim Jul 15 '16 at 06:12
  • @LưuVĩnhPhúc not sure it is a duplicate as that answer doesn't really address 2D arrays (or if it does I didn't look hard enough ;-) – John3136 Jul 15 '16 at 06:21

1 Answers1

0

Initializing elements of an array to 0 is simple.

double cache[100][100] = {};

Initializing them to -1 is not easy. You'll have to have the entire array written out as:

double cache[100][100] = {-1, repeat 10000 times};

You can set them to -1 using:

std::fill(cache[0], cache[0]+100*100, -1);
R Sahu
  • 204,454
  • 14
  • 159
  • 270