Range Pipelining with Temporary Containers Using Range-V3
Problem:
You have a range of elements (src) and a third-party function (f) that takes an element of the range as input and returns a vector. You want to transform each element in the range using f and flatten the resulting vectors into a single range. However, using view::transform and view::join directly won't work because views cannot be created for temporary containers.
Solution:
To support such pipelines, range-v3 introduces the views::cache1 operator. This operator allows you to store the results of a view in a temporary container and then create a view of that container. By including views::cache1 in the pipeline, you can create a view of the flattened vectors:
auto rng = src | views::transform(f) | views::cache1 | views::join;
Code Sample:
The following code sample demonstrates how to use views::cache1 to create a range pipeline that transforms and flattens elements from a range:
<code class="cpp">#include <range/v3/view.hpp> #include <range/v3/algorithm.hpp> #include <vector> std::vector<std::string> f(int i) { return std::vector<std::string>(i, char('a' + i)); } int main() { auto rng = views::iota(0, 4) | views::transform([](int i) { return f(i); }) | views::cache1 | views::join('-'); check_equal(rng, {'-', 'b', '-', 'c', 'c', '-', 'd', 'd', 'd'}); CPP_assert(input_range<decltype(rng)>); CPP_assert(!range<const decltype(rng)>); CPP_assert(!forward_range<decltype(rng)>); CPP_assert(!common_range<decltype(rng)>); return 0; }</code>
The above is the detailed content of How Can I Flatten Vectors Returned from a Function Using Range-V3 Pipelines?. For more information, please follow other related articles on the PHP Chinese website!