Row-major vs Column-major confusion

后端 未结 9 1502
离开以前
离开以前 2021-01-31 19:27

I\'ve been reading a lot about this, the more I read the more confused I get.

My understanding: In row-major rows are stored contiguously in memory, in column-major colu

9条回答
  •  误落风尘
    2021-01-31 19:58

    Given the explanations above, here is a code snippet demonstrating the concept.

    //----------------------------------------------------------------------------------------
    // A generalized example of row-major, index/coordinate conversion for
    // one-/two-dimensional arrays.
    // ex: data[i] <-> data[r][c]
    //
    // Sandboxed at: http://swift.sandbox.bluemix.net/#/repl/5a077c462e4189674bea0810
    //
    // -eholley
    //----------------------------------------------------------------------------------------
    
    // Algorithm
    
    let numberOfRows    = 3
    let numberOfColumns = 5
    let numberOfIndexes = numberOfRows * numberOfColumns
    
    func index(row: Int, column: Int) -> Int {
        return (row * numberOfColumns) + column
    }
    
    func rowColumn(index: Int) -> (row: Int, column: Int) {
        return (index / numberOfColumns, index % numberOfColumns)
    }
    
    //----------------------------------------------------------------------------------------
    
    // Testing
    
    let oneDim = [
           0,    1,    2,    3,    4,
           5,    6,    7,    8,    9,
          10,   11,   12,   13,   14,
    ]
    
    let twoDim = [
        [  0,    1,    2,    3,    4 ],
        [  5,    6,    7,    8,    9 ],
        [ 10,   11,   12,   13,   14 ],
    ]
    
    for i1 in 0..

提交回复
热议问题