简体   繁体   中英

Implement 2d array coordinates in 1d array in C++

The code inside the for loop is for the x and y (j and i) "coordinates" from a 2d array. How could I implement this neighbor/index finding in a 1d array? I think I could implement it for the first four equations. But i'm confused as how to implement up-left etc.

for(int i=0; i<cols*rows; i++){
        //Counts current index's 8 neigbour int values
      int count=0;
      int x = i%cols;
      int y = i/rows;
      //rows y i
      //cols x j

      count+= [grid][i][(j-1+cols)%cols] //left
         +[grid][i][(j+1+cols)%cols]    //right
         +[grid][(i-1+rows)%rows][j]    //up
         +[grid][(i+1+rows)%rows][j]    //down
         +[grid][(i-1+rows)%rows][ (j-1+cols)%cols]  //up-left
         +[grid][(i+1+rows)%rows][ (j+1+cols)%cols]  //down-right
         +[grid][(i+1+rows)%rows][ (j-1+cols)%cols]  //down-left
         +[grid][(i-1+rows)%rows][ (j+1+cols)%cols] ;//up-right
}

Starting with a 1-D vector:

int rows = 10;
int cols = 10;
vector<int> grid(rows * cols);

You can manage this in different ways, example

for(int y = 0; y < rows; y++)
{
    for(int x = 0; x < cols; x++)
    {
        int point = grid[y * rows + x];
    }
}

Where you can access any point at any given x and y in a 2-dimensional plane.

Top-left is:

x = 0;
y = 0;

bottom-right is

x = cols - 1;
y = rows - 1;

And so on.

Use a function like this

inline int idx(const int i, const int j, const int rows) const
{
    return i * rows + j;
}

to convert the 2d indices to 1d indices. This way you don't have to change your algorithm.

Usage would be grid[idx(i, (j-1+cols)%cols, rows)] .

The basic formula for computing the 1d coordinate from the 2d index pattern is usually one of the following:

  • row_index * row_length + column_index
  • column_index * column_length + row_index

Which one applies to your case depends on whether you would like to have a row-based or column-based memory layout for your 2d array . It makes sense to factor out the computation of this index into a separate function, as suggested in the other answer .

Then you just need to fill in the values somehow.

You could do it like this, for example:

// iterate big picture
// TODO: make sure to handle the edge cases appropriately
for (int i_row = 1; i_row < n_rows - 1; i_row++) {
    for (int i_col = 1; i_col < n_cols -1; i_col++) {
        // compute values
        dst[i_row*n_cols+i_col] = 0;
        for (int r = i_row-1; r < i_row+2; r++) {
            for (int c = i_col-1; c < i_col+2; c++) {
                dst[i_row*n_cols+i_col] += src[r*n_cols + c];
            }
        }
    }
}

Assuming src and dst are distinct 1d vectors of size n_rows*n_cols ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM