nikitablack
nikitablack

Reputation: 4663

How to concat two existing ranges::view?

I want to use an existing view for concatenation. In code:

auto rng = view::empty<vector<int>>();

for(int i{0}; i < 5; ++i)
{
    vector<int> const & v{foo()}; // returns a reference
    rng |= view::concat(v); // doesn't compile - error: no viable overloaded '|='
};

In other words - how can I create a view to multiple vectors whose number is not known until runtime?

Upvotes: 5

Views: 4237

Answers (1)

Eric Niebler
Eric Niebler

Reputation: 6177

You can't compose views this way. Concatenating a view yields an object with a different type. You can't assign it back to the original view because its type is different.

You can get the effect you're after with a combination of view::cycle (takes one range and repeats it infinitely), and view::take (takes the first N elements of a range).

vector<int> const & v{foo()}; // returns a reference
auto rng = v | view::cycle | view::take(5 * v.size());

EDIT

If foo() can return a reference to a different vector each time, then you can use view::generate and view::join, in addition to view::take:

auto rng = view::generate(foo) | view::take(5) | view::join;

Upvotes: 9

Related Questions