std::ranges::cache_latest — cache the latest element for multiple reads.
1#include <ranges>23std::vector<int> v = {1, 2, 3, 4, 5};45// Without cache (re-evaluates on each access)6auto transform_view = v7 | std::views::transform([](int x) {8 std::cout << "Computing " << x << "\n";9 return x * x;10 });1112// With cache (evaluates once)13auto cached = v14 | std::views::transform([](int x) {15 std::cout << "Computing " << x << "\n";16 return x * x;17 })18 | std::views::cache_latest;1920// Multiple reads only compute once21auto it = cached.begin();22std::cout << *it; // Computing 123std::cout << *it; // No re-computation24std::cout << *it; // No re-computation2526// Useful for expensive computations27auto primes = std::views::iota(2)28 | std::views::transform([](int n) {29 // Expensive primality test30 return is_prime(n) ? std::optional(n) : std::nullopt;31 })32 | std::views::filter([](auto opt) { return opt.has_value(); })33 | std::views::transform([](auto opt) { return *opt; })34 | std::views::cache_latest;3536// Iterate primes37for (int p : primes | std::views::take(10)) {38 std::cout << p << " ";39}
Benefits: