简体   繁体   中英

Negative X,Y Coordinates to linear array index?

I have been (unsuccessfully ) attempting to convert the negative coordinates of a 2d coordinate grid into a linear index intended for placing within an array.

std::vector<float> heights(20*20);
for ( int x = -10; x < 10; x++ ) {
    for ( int y = -10; y < 10; y++ ) {
        heights[20*x + y] = NoiseGenerator.GetPerlinFractal(x, y);
    }
}

The above is a simplified version of what I was doing before I attempted to use negative coordinates.

Honestly, I'm at a loss. This seems like it should be extremely simple to solve, but here I am feeling stupid after a solid 2 hours of no results and plenty of out_of_range exceptions :)

I'd appreciate any help anyone can give me. Thanks in advance!

How about heights[(x - x_min) * rows + (y - y_min)] ?

Here x_min and y_min are both -10, and rows is 20.

Note that x_max and y_max will both be 9, as you allow 20 points in each dimension. 21 would have been more symmetric.

Recovering x and y from a given index in your vector will require using integer division and % .

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