With the latest C++ Standard recently completed at the time of writing, and ready for the final vote, this article continues the theme of exploring the latest new features and how they can be best utilized. The <ranges> header is a comparatively recent addition to the Standard Library (since C++20) and has seen some recent updates, and in this article we will explore its enhanced features and functionality.
1. Concatenating views
Taking a view of a range is often very useful, providing an abstraction to inspect (and manipulate) elements within it. Being able to concatenate them was not previously possible, but the following code demonstrates the idea (tested with the trunk version of the GCC C++ compiler with flag -std=c++26):
#include <ranges>
#include <print>
using namespace std;
using namespace std::ranges;
int main() {
auto init_list = { 1, 2, 3 };
auto inf_list = views::iota(4);
auto vw = views::concat(init_list, inf_list)
| views::take(5);
println("{}", vw); // Outputs: [1, 2, 3, 4, 5]
}
This program demonstrates the concatenation of two views (the second being infinite) before taking five elements and outputting them, which is a greater number than present in the first view. Obviously this method is only useful if the first view’s data is bounded, and both views must access data with compatible types (usual numerical promotion rules apply). Attempting to take more elements than present in both views will fail silently (the view will be truncated).
2. Use of std::optional as a view
The concept of projecting std::optional as a view is simple: an empty view represents std::nullopt, while a view of length one represents an optional value being present. This functionality is probably made more useful by the availability of view concatenation (see above):
#include <ranges>
#include <optional>
#include <print>
using namespace std;
using namespace std::ranges;
void f(std::optional<int> opt) {
auto vw = views::concat(opt, views::iota(10, 15))
| views::take(4);
println("{}", vw);
}
int main() {
f(nullopt); // Outputs: [10, 11, 12, 13]
f(99); // Outputs: [99, 10, 11, 12]
}
Concatenating more than one optional value with (more than) one view is possible, as views::concat() can accept any number of views as parameters.
3. Performance enhancement with caching
Ranges are lazy, the key to their efficiency is that values at each stage in the pipeline are only calculated when they are needed. Previously there were limits to this meaning that some calculations could need to be performed more than once depending upon the pipeline. The following program shows the filtering of even square numbers both with and without the new views::cache_latest together with diagnostics which track the calculations being made:
#include <print>
#include <ranges>
#include <vector>
using namespace std;
using namespace std::ranges;
int main() {
auto square = [](int i) {
print("transform: {} | ", i);
return i * i;
};
auto is_even = [](int i) {
print("filter: {} | ", i);
return i % 2 == 0;
};
vector<int> v = {1, 2, 3, 4, 5};
// No caching of the transform result before filtering
auto even_squares = v
| views::transform(square)
| views::filter(is_even);
// Cache the transform result before filtering
auto even_squares_cache = v
| views::transform(square)
| views::cache_latest // <-- C++26
| views::filter(is_even);
println("Without views::cache_latest");
for (int n : even_squares) {
println("result: {}", n);
}
print("\n\n");
println("With views::cache_latest");
for (int n : even_squares_cache) {
println("result: {}", n);
}
print("\n\n");
}
The output from running this program is:
Without views::cache_latest
transform: 1 | filter: 1 | transform: 2 | filter: 4 | transform: 2 | result: 4
transform: 3 | filter: 9 | transform: 4 | filter: 16 | transform: 4 | result: 16
transform: 5 | filter: 25 |
With views::cache_latest
transform: 1 | filter: 1 | transform: 2 | filter: 4 | result: 4
transform: 3 | filter: 9 | transform: 4 | filter: 16 | result: 16
transform: 5 | filter: 25 |
As demonstrated the ranges have to “backtrack” and re-evaluate the transform (squaring) of both 2 and 4 before getting the results 4 and 16 respectively unless views::cache_latest is utilized. This caches the result of the most recent dereference (that is, it evaluates the underlying element once and stores it internally), and when the iterator advances, the cached entry is cleared. Repeated dereferences at the same iterator position return the cached value without re-evaluating.
This doesn’t quite come “for free”, as there are some important semantics and constraints to consider:
- Thread Safety: Because
operator*mutates the view’s internal cache, reading from the samecache_latest_viewinstance across multiple threads concurrently is a data race unless synchronized externally - Always an input_range: Even if the underlying range is a
forward_rangeorrandom_access_range,cache_latest_viewdegrades the category toinput_range - Not a borrowed_range: The elements returned by dereferencing are references to internal cache storage inside the view object itself. Therefore, iterators cannot outlive the view.
- Placement Matters: Place
std::views::cache_latestimmediately after the lazy evaluation you wish to cache, and before the view or algorithm that re-inspects it (e.g.,views::filter,views::take_while, or multiple manual dereferences). Placing it before an expensive view does nothing to prevent repeated execution.
4. Direct random number generation
C++ has had its own random engine library since C++11, but previously this was not integrated within ranges and views. The class std::ranges::generate_random is provided in the same <random> header, offering several advantages over using std::ranges::generate for this purpose, and having four primary overloads:
// 1. Whole Range with Distribution
template<class R, class G, class D>
constexpr borrowed_iterator_t<R>
generate_random(R&& r, G&& g, D&& d);
// 2. Iterator/Sentinel with Distribution
template<class G, class D, output_iterator<...> O, sentinel_for<O> S>
constexpr O
generate_random(O first, S last, G&& g, D&& d);
// 3. Whole Range with Raw Generator (no distribution)
template<class R, class G>
constexpr borrowed_iterator_t<R>
generate_random(R&& r, G&& g);
// 4. Iterator/Sentinel with Raw Generator (no distribution)
template<class G, output_iterator<...> O, sentinel_for<O> S>
constexpr O
generate_random(O first, S last, G&& g);
To generate ten numbers between one and a hundred, it is possible to use code such as below (although this was not available in GCC trunk, including <experimental/random>, when this article was written):
#include <ranges>
#include <random>
#include <array>
#include <print>
using namespace std;
using namespace std::ranges;
int main() {
array<int, 10> random_ints;
mt19937 gen{random_device{}()};
uniform_int_distribution<int> dist{0, 100};
// Fills random_ints with 10 values uniformly distributed in [0, 100]
generate_random(random_ints, gen, dist);
println("{}", random_ints); // Outputs: [83, 25, 48, 15, 9, 60, 47, 31, 91, 54]
}
For a more involved approach using one of the available number distributions:
#include <random>
#include <vector>
#include <ranges>
using namespace std;
using namespace ranges;
int main() {
vector<double> measurements(100);
mt19937_64 gen{42};
normal_distribution<double> normal{0.0, 1.0};
// Populate only the first half
generate_random(
measurements.begin(),
measurements.begin() + 50,
gen,
normal
);
// And the second half using a subrange view:
auto second_half = measurements | views::drop(50);
generate_random(second_half, gen, normal);
}
The availability of this new functionality becomes useful for a number of reasons:
- Customization Hooks for Batch Execution:
std::ranges::generate_randomincludes customization points, so custom or hardware-accelerated RNG backends providing a.generate_random()member function allow the algorithm to delegate to batch generation rather than looping scalar elements. - SIMD and GPU Optimization: By handing the entire range, engine, and distribution to a single function call, standard library implementations and optimizing compilers can generate multiple numbers simultaneously using AVX/NEON vector instructions.
- Synergy with C++26
std::philox_engine: C++26 also adds the Philox counter-based random engine. Counter-based engines are naturally vectorizable and parallelizable because every index can be computed independently without sequentially chaining state updates. Pairingstd::philox_enginewithstd::ranges::generate_randomgives massive throughput gains in Monte Carlo and machine learning workloads.
Summary
That just about wraps up this article on improvements to C++26 views from the Ranges library. Ideally you’ll be able to use all of the features described in your chosen C++ compiler very soon, as implementation continues apace.