0 Tage Serie
cpp / intermediate
Snippet

Row-Major-Indizierung für flache Matrizen

Die Darstellung eines 2D-Gitters als 1D-Array verbessert die Speicherlokalität. Die Row-Major-Indizierung (Reihe * Gesamtspalten + Spalte) bildet 2D-Koordinaten korrekt auf 1D-Offsets ab.

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 performance
std::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;
}
Erklärung
1
std::vector<int> matrix(rows * cols, 0);
Alloziert einen zusammenhängenden Speicherblock, der groß genug für alle Gitterelemente ist.
2
matrix[r * cols + c] = 42;
Berechnet den linearen Index basierend auf der Zeile und der Anzahl der Spalten pro Zeile.