CKTIS / C++
std::ranges::to — constructing a container from a range
C++23 std::ranges::to constructs an object, usually a container, from an input range. It lets you finish a view pipeline with a concrete result, specifying either the full container type or a template whose arguments will be deduced.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::ranges::to<C>(range, args...)
range | std::ranges::to<C>(args...)
std::ranges::to<ContainerTemplate>(range, args...)
range | std::ranges::to<ContainerTemplate>(args...)std::ranges::to, available since C++23 in <ranges>, constructs a result from a range satisfying input_range. For a container such as std::vector<int>, it materializes elements rather than creating another lazy view. The destination type C must be a cv-unqualified class type and must not satisfy view.
The expression std::ranges::to<std::vector<int>>(range) specifies the result type explicitly. The form std::ranges::to<std::vector>(range) uses class template argument deduction. In a pipeline, use range | std::ranges::to<std::vector<int>>(): the () creates a pipeline closure object. Additional args..., such as an allocator, are forwarded to the selected container constructor.
For directly convertible elements, the function tries, in order: a constructor accepting the range, a constructor tagged with std::from_range, a suitable iterator-pair constructor, and finally construction from args... followed by element insertion. Each path has its own requirements. Nested ranges can be converted recursively; if no permitted path applies, the program is ill-formed.
The example constructs a std::vector<int> containing the squares of 1 through 5; the upper bound of std::views::iota(1, 6) is exclusive. Materializing this pipeline traverses its elements, so do not use an unbounded range without limiting its element count. A library implementation supporting this C++23 feature is required: the repository compiler flag alone does not attest production-runtime support. The supplied reference is a developing standard draft, not a frozen C++23 edition.
Examples
#include <cstddef>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
auto values = std::views::iota(1, 6)
| std::views::transform([](int n) { return n * n; })
| std::ranges::to<std::vector<int>>();
for (std::size_t i = 0; i < values.size(); ++i) {
if (i != 0) std::cout << ' ';
std::cout << values[i];
}
std::cout << '\n';
}
Result
1 4 9 16 25
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.