Блог пользователя rezaulhsagar

Автор rezaulhsagar, история, 7 лет назад, По-английски

Hi, In a graph problem, I need to memset a whole 2D array with a large value that denotes INFINITY.

Currently, I am doing this by running a O(N*N) loop.

const int maxx = something;
int grid[maxx+7][maxx+7];
for(int i=0;i<maxx;i++){
   for(int j=0;j<maxx;j++){
      grid[i][j] = large_value;
   }
}

Is there a better way to do this?

Also, I have tried memset function.

memset(grid,127,sizeof grid) resets all values to 2139062143

memset(grid,128,sizeof grid) resets all values to -2139062144

Why memset works like this?

Thanks in advance!

  • Проголосовать: нравится
  • -1
  • Проголосовать: не нравится

»
7 лет назад, # |
Rev. 2   Проголосовать: нравится -26 Проголосовать: не нравится

You can use memset, but in a different way

memset (a, large_value, sizeof(a[0][0]) * size_arr * size_arr);
»
7 лет назад, # |
  Проголосовать: нравится +10 Проголосовать: не нравится

memset is to manipulate bytes. A byte is 8 bits, and the binary of 127 is 1111111(28 - 1), so memset(127) is to make all bytes of the array be 01111111. A int is 4 bytes, so the manipulation can make the element of this array be 01111111011111110111111101111111, which is just 2139062143. Sorry for my poor English.

»
7 лет назад, # |
  Проголосовать: нравится +16 Проголосовать: не нравится

memset works byte by byte and not 'element' by 'element' (in your case int).

There is no way (in C++) of setting all values in a 2D-array to some constant (unless you write your own function(s)).

»
7 лет назад, # |
  Проголосовать: нравится +18 Проголосовать: не нравится
fill(&grid[0][0], &grid[0][0] + (maxx + 7) * (maxx + 7), large_value);
»
7 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

Why not make 2139062143 or other memsetable value your infinity?