代码之家  ›  专栏  ›  技术社区  ›  justin

索引转换:行主坐标到笛卡尔坐标(例如,像素)

  •  2
  • justin  · 技术社区  · 15 年前

    我需要将内存索引转换/访问行主布局和笛卡尔布局。

    如果这有助于你想象用途或问题:情况是访问存储在不同内存布局中的像素(读取/操作)。

    一个小程序来说明:

    #include <cassert>
    #include <iostream>
    
    /*
    memory layout:
        row major:
            0 1 2 3
            4 5 6 7
            8 9 10 11
    
        cartesian:
            2 5 8 11
            1 4 7 10
            0 3 6 9
    */
    
    unsigned rowmaj_to_cartesian(const unsigned& i) {
        return ?;
    }
    
    int main(int argc, const char* argv[]) {
    
        const unsigned W(4);
        const unsigned H(3);
        const unsigned A(W * H);
    
        unsigned a[A];
    
        for (size_t i(0); i < A; ++i) {
            /* populate a[] with row-major layout */
            a[i] = i;
        }
    
        for (size_t i(0); i < A; ++i) {
            /* convert the index values to cartesian layout */
            a[i] = rowmaj_to_cartesian(a[i]);
            std::cout << i << ": " << a[i] << "\n";
        }
    
        /* sanity check the results */
        assert(a[0] == 2);
        assert(a[1] == 5);
        assert(a[2] == 8);
        assert(a[3] == 11);
    
        assert(a[4] == 1);
        assert(a[5] == 4);
        assert(a[6] == 7);
        assert(a[7] == 10);
    
        assert(a[8] == 0);
        assert(a[9] == 3);
        assert(a[10] == 6);
        assert(a[11] == 9);
    
        return 0;
    }
    

    这是一个简单的问题,但是我还没有找到答案。

    谢谢你的帮助!

    细节:

    1)对不起,不能选择外部库。(也许这个例子不好:stl也不是一个选项)

    2)我所说的笛卡尔是 不 少校。

    *也许有更好的说法?

    1 回复  |  直到 15 年前
        1
  •  4
  •   lijie    15 年前

    从原来的索引转换为行列: r = i/WIDTH, c = i%WIDTH 然后对笛卡尔标引: c*HEIGHT + (HEIGHT-1-r) .