Home / Forums / How do C++20 Ranges (std::views) avoid intermediate container allocations? [Part 2]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How do C++20 Ranges (std::views) avoid intermediate container allocations? [Part 2]

AudioDspCoder
Audio Signal Processing
MEMBER
Rep: 183
Join Date: Sep 2022
Posts: 6
Thanks: 98
3y ago · Sep 16, 2022 2:44 PM
#1
How does std::views::filter and std::views::transform work under the hood without creating temporary vector allocations like LINQ or JavaScript array methods do?
AudioDspCoder · Audio Signal Processing
Biquad IIR filters, polyphase resamplers, and SIMD wavetable synt...
The following users thanked AudioDspCoder for this post:
VoxelCoder
Voxel World Architect
MEMBER
Rep: 179
Join Date: Feb 2021
Posts: 6
Thanks: 64
3y ago · Sep 16, 2022 6:16 PM
#2
std::views are non-owning, lazy evaluated iterators! When you write auto result = vec | std::views::filter(isEven) | std::views::transform(square);, no calculations happen until you actually iterate the range. The iterator computes the filter/transform on-the-fly during dereferencing (*it).
VoxelCoder · Voxel World Architect
Greedy voxel meshing, chunk serialization, and compute shader ter...
FlatMapFan
Cache-Friendly Containers
MEMBER
Rep: 353
Join Date: Oct 2023
Posts: 6
Thanks: 97
3y ago · Sep 16, 2022 7:16 PM
#3
They are pure zero-allocation views with zero memory overhead, and the compiler can inline the entire pipeline into a single tight machine loop!
FlatMapFan · Cache-Friendly Containers
Sorted vector flat_map vs red-black tree std::map benchmarks in h...