0 day streak
cpp / expert
Snippet

N-Dimensional Index Linearization for High-Performance Arrays

Expert pattern for handling multi-dimensional data in a single flat memory block. Linearization improves cache locality and performance compared to nested pointers (arrays of arrays), which cause pointer chasing.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
template <typename T, size_t W, size_t H, size_t D>
class Tensor {
T data[W * H * D];
public:
T& operator()(size_t x, size_t y, size_t z) {
// Index linearization formula: z * (Width * Height) + y * Width + x
return data[z * (W * H) + y * W + x];
}
constexpr size_t size() const { return W * H * D; }
};
Breakdown
1
T data[W * H * D];
Allocates a single contiguous block of memory for all dimensions.
2
data[z * (W * H) + y * W + x]
Calculates the exact 1D offset from 3D coordinates (x, y, z).