cpp / intermediate
Snippet
Row-Major Indexing for Flattened Matrices
Representing a 2D grid as a 1D array improves memory locality. Row-major indexing (row * total_columns + column) correctly maps 2D coordinates to 1D offsets.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>#include <vector>int main() {int rows = 3, cols = 4;// Using a 1D vector to represent a 2D matrix for better performancestd::vector<int> matrix(rows * cols, 0);// Accessing element at [row 1, col 2]int r = 1, c = 2;matrix[r * cols + c] = 42;std::cout << "Value at (1,2): " << matrix[r * cols + c] << std::endl;return 0;}
Breakdown
1
std::vector<int> matrix(rows * cols, 0);
Allocates a contiguous block of memory large enough for all grid elements.
2
matrix[r * cols + c] = 42;
Calculates the linear index based on the row and the number of columns per row.