Starting from C++23, standard containers support a new set of constructor overloads. These constructors take a
std::from_range
tag, a range and an optional allocator. These from_range
constructors make it easier to construct containers from ranges, helping make C++ code more concise, more expressive, and less error-prone.
Constructing Containers from Ranges in C++23
by Sandor Dargo
From the article:
I’ve written plenty on this blog about standard algorithms, but far less about ranges. That’s mostly because, although I’ve had production-ready compilers with C++20 ranges since late 2021, the original ranges library lacked a few key capabilities.
The biggest gap was at the end of a pipeline: you could transform data lazily, but you couldn’t drop the result straight into a brand-new container. What you got back was a view; turning that view into, say, a
std::vector
still required the old iterator-pair constructor.C++23 fixes that in two complementary ways:
std::to
(an adaptor that finishes a pipeline by converting to a container), andfrom_range
constructors on every standard container.Today we’ll focus on the second improvement, because it’s the one you can implement in your own types, too.
The
from_range
constructorEvery standard container now supports a new set of constructors that make integration with ranges smoother — the so-called
from_range
constructors.These constructors allow you to build a container directly from a range, rather than from a pair of iterators.
Add a Comment
Comments are closed.