CKTIS / C++
Array of structures (AoS) in C++
AoS stores complete records side by side, whereas SoA groups each field into its own array. Which layout fits depends on how the program accesses the data.
Version: ISO C++23; implementation support may vary
Syntax
struct Sample { int value; char quality; };
std::array<Sample, 3> aos{};
struct Columns {
std::array<int, 3> value;
std::array<char, 3> quality;
};
Columns soa{};
// For 0 <= i < 3: aos[i].value (AoS), soa.value[i] (SoA).An array of structures (AoS) groups data by record. In std::array<Sample, 3>, three elements of type Sample occupy consecutive slots in memory. aos[i].value selects a record and then its member. The byte stride from one record's start to the next is sizeof(Sample), including any padding. The value members do not form an int array: do not use pointer arithmetic from &aos[0].value to reach them.
A structure of arrays (SoA) groups data by field. Each field has its own contiguous array, or column. soa.value[i] and soa.quality[i] describe the same logical record. When inserting, removing, or reordering records, keep the indices in sync across columns.
In data-oriented design, choose a layout for the dominant access pattern. AoS keeps the fields of one record together. If a loop reads only value, SoA stores this frequently accessed (hot) column without interleaving it with quality. More useful values can then fit in a cache line, which can improve cache locality. Neither layout guarantees a speedup.
AoS and SoA are ordinary data layouts, not distinct C++23 language constructs. Before switching layouts, measure on the target hardware with representative data and workloads. Include the conversion cost if the application performs a conversion.
Examples
#include <array>
#include <cstddef>
#include <iostream>
constexpr std::size_t count = 3;
struct Sample {
int value;
char quality;
};
struct Columns {
std::array<int, count> value;
std::array<char, count> quality;
};
int main() {
const std::array<Sample, count> aos{{{4, 'A'}, {7, 'B'}, {10, 'A'}}};
Columns soa{};
for (std::size_t i = 0; i < aos.size(); ++i) {
soa.value[i] = aos[i].value;
soa.quality[i] = aos[i].quality;
}
int aos_sum = 0;
for (const Sample& sample : aos) {
aos_sum += sample.value;
}
int soa_sum = 0;
for (int value : soa.value) {
soa_sum += value;
}
std::cout << "AoS: " << aos_sum << '\n'
<< "SoA: " << soa_sum << '\n';
}
Result
AoS: 21 SoA: 21
The program copies both fields into SoA columns, then sums only `value` in each layout. Both sums are 21; this demonstrates equivalent results, not performance.
Related lessons
- C++ · Lesson 21 · Advanced · Version: 3
Sources
- N4950 — Working Draft, Standard for Programming Language C++ (C++23)
- C++ working draft — Overview of std::array [array.overview]
- C++ working draft — Sizeof [expr.sizeof]
- C++ working draft — Additive operators [expr.add]
- WG21 P2996R12 — Reflection for C++26, §3.10 Struct to Struct of Arrays (layout example)