In C++23, how do you turn a views pipeline such as std::views::iota or std::views::split into a std::vector, and why must you?
answer
- views are not containers
- C++23 adds a converter
- pipe into it
- before C++23, the iterator-pair constructor
- split yields subranges
basics
~20 sA view only describes elements, so to store, index or return the results you materialise them. C++23's std::ranges::to does it: v | std::ranges::tostd::vector(). In C++20 you construct the container from the view's iterators or loop with push_back.
solid answer
~40 sA view such as `std::views::iota(1, 4)` or `line | std::views::split(',')` produces elements on demand and usually refers to its source, so it cannot be kept after the source dies, may not support indexing or `size()`, and recomputes on every pass. When you need a real container, C++23's `std::ranges::to<C>(r)` - or the pipe form `r | std::ranges::to<C>()` - builds one, deducing the element type when you write `std::ranges::to<std::vector>()`. It also converts nested ranges: `split` yields subranges of characters, which you turn into `std::string_view` (C++23's range constructor) or `std::string` before collecting. In C++20, construct from iterators - `std::vector<T>(v.begin(), v.end())` when the view is a common range, or `std::ranges::copy(v, std::back_inserter(out))` otherwise. Feature-test with `__cpp_lib_ranges_to_container`; libstdc++ added `ranges::to` in 14.1 and libc++ in 17.
code
cpp · 18 lines#include <iostream>
#include <ranges>
#include <string>
#include <string_view>
#include <vector>
int main() {
std::string_view line = "21.5,98.0,22.1";
// C++23: materialize each lazy piece and the outer range
auto fields = line | std::views::split(',')
| std::views::transform([](auto piece) { return std::string_view(piece); })
| std::ranges::to<std::vector<std::string>>();
auto ids = std::views::iota(1, 4) | std::ranges::to<std::vector>(); // {1, 2, 3}
std::cout << fields.size() << ' ' << fields[1] << ' ' << ids.back() << '\n';
}go deeper
Know that a view is not a container, and that C++23 converts one with v | std::ranges::tostd::vector().
Explain why views must be materialised to be stored or indexed, what split yields, and the C++20 iterator or copy fallbacks.
Place materialisation at lifetime boundaries, avoid dangling string_view fields, and feature-test ranges::to across standard libraries.
Standardise one materialisation helper for codebases that span C++20 and C++23 toolchains so call sites do not fork on the standard version.
## Why a view is not enough A view is a recipe plus a reference. That is ideal for one pass close to the data, and a problem whenever the results must persist: - **Lifetime.** A pipeline over a local `std::string` or `std::vector` refers to it; storing the view in a member or returning it outlives the source. - **Capabilities.** `views::filter` gives no `size()` and no random access, and a split view yields subranges, not strings. - **Repeated work.** Every iteration re-runs the predicates and transforms. **Materialising** - copying the produced elements into a container - fixes all three at the cost of one allocation and one pass. ## C++23: std::ranges::to C++23 adds `std::ranges::to` in `<ranges>`: ```cpp auto ids = std::views::iota(1, 4) | std::ranges::to<std::vector>(); // std::vector<int>{1, 2, 3} auto hot = readings | std::views::filter(isHot) | std::ranges::to<std::vector<Reading>>(); ``` Points to know: - **Two spellings.** `std::ranges::to<C>(r)` and the pipeable `r | std::ranges::to<C>()`. - **Deduction.** `std::ranges::to<std::vector>()` names the template without arguments and deduces the element type from the range. - **Any container.** `std::ranges::to<std::set>()`, `std::ranges::to<std::string>()`, or a map from a range of pairs. - **Efficient construction.** It constructs the container directly from the range when it can, then tries a `std::from_range` constructor, then an iterator pair for common ranges, and otherwise appends element by element, reserving first when the size is known. C++23 added `from_range` constructors and `append_range`/`insert_range` members to the standard containers for this. - **Nested ranges.** When the elements are themselves ranges, it converts them recursively if the target's element type needs it. ## Splitting a telemetry line A sensor sends `"21.5,98.0,22.1"`. `std::views::split(',')` yields one **subrange** of characters per field - a view into the original string, not a string. To keep the fields, convert each piece and then the whole: 1. `line | std::views::split(',')` - a lazy range of subranges. 2. `| std::views::transform([](auto piece) { return std::string_view(piece); })` - C++23 added a constructor from a contiguous range, so a `std::string_view` is cheap and still points into `line`. 3. `| std::ranges::to<std::vector<std::string>>()` - each `string_view` becomes an owning `std::string`, so the result survives `line`. In C++20 mode the `std::string_view(piece)` step fails to compile - Apple clang 21 reports "no matching conversion for functional-style cast from 'std::ranges::subrange<const char *>' to 'std::string_view'" - and `std::ranges::to` does not exist. Note also that `views::split` was redesigned after C++20 shipped, as a defect report, and the original lazy behaviour was renamed `views::lazy_split`; older standard libraries may still ship the original split. ## C++20 fallbacks | Situation | C++20 code | |---|---| | View is a common range (same iterator and sentinel type) | `std::vector<T> out(v.begin(), v.end());` | | View is not common, such as `iota` with no bound | `std::ranges::copy(v, std::back_inserter(out));` | | Need a common range for an old API | `v | std::views::common` | A helper template in the codebase that uses `std::ranges::to` when `__cpp_lib_ranges_to_container` is defined and falls back to the copy otherwise keeps call sites identical across standard libraries. `std::ranges::to` first shipped in libstdc++ 14.1 and in libc++ 17. ## Choosing the target container `std::ranges::to` makes the target an explicit decision, which is a good moment to ask what the data is for: - **`std::vector`** for ordered results that will be iterated or indexed; it is the default for a reason. - **`std::set` or `std::flat_set`** (C++23) when the next step is membership tests or deduplication; `std::ranges::to<std::set>()` deduplicates as it collects. - **`std::string`** for character ranges: `chars | std::ranges::to<std::string>()` joins a filtered or transformed character sequence back into text. - **`std::map`** from a range of pairs, for example `ids | std::views::transform(makePair) | std::ranges::to<std::map>()`. Extra arguments are forwarded to the container's constructor, so an allocator or a comparator can be supplied: `std::ranges::to<std::set<int, std::greater<>>>()` builds a descending set. ## When not to materialise If the pipeline is consumed once, immediately, by a loop or an algorithm, materialising only adds an allocation. Keep it lazy there, and convert at the boundary where data is stored, returned, indexed or shared.
- Why convert each split piece to std::string before storing it, rather than keeping std::string_view?A `std::string_view` built from a split piece still points into the original line. If the line was a temporary buffer from the network or a reused read buffer, every stored view dangles once it is overwritten. Converting to `std::string` copies the characters, so the container owns its data. Keep `string_view` only when the source outlives the container.
- How do you collect a C++20 views::iota(0) | views::take(5) into a std::vector without ranges::to?`std::views::iota(0) | std::views::take(5)` is not a common range (its sentinel type differs from its iterator type), so the iterator-pair vector constructor does not accept it. Use `std::ranges::copy(r, std::back_inserter(out))`, or adapt it with `std::views::common` first and then construct `std::vector<int>(c.begin(), c.end())`.
- Storing a views pipeline in a member as if it were a container
- Expecting views::split to yield std::string elements
- Calling size() on a filter view
- Claiming std::ranges::to is available in C++20
- Materialising every pipeline even when it is consumed once
Assumes C++23; std::ranges::to and std::string_view's range constructor are C++23, views::iota and views::split are C++20 (split revised by a defect report).