6

Consider the following case:

std::vector<int> v{0, 1, 2, 3, 4, 5};
// 0 1 2 3 4 5
auto rng1 = std::views::all(v);
// 5 4 3 2 1 0
auto rng2 = std::views::reverse(v);
// 4 2 0
auto rng3 = std::views::filter(rng2, [](int x){return x % 2 == 0;});

Is there a elegant way to concatenate those three adaptors into one single view like this:

// 0 1 2 3 4 5 5 4 3 2 1 0 4 2 0
auto final_rng = std::views::concat(rng1, rng2, rng3);

It seems impossible since rng1, rng2, and rng3's are very different types.

Can someone give an alternative solution? thanks.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • It's certainly possible. I don't see it in the standard library, but this would be `my_concat`, whose iterators are basically a `variant`. – Justin Jun 18 '20 at 17:59

2 Answers2

4

Yes, what you wrote just in a different namespace - there's no concat in the Standard Library but there is one in range-v3:

auto final_rng = ranges::views::concat(rng1, rng2, rng3);

The fact that the ranges are different types doesn't pose a problem. You just have an iterator that's built up of a variant of the underlying iterators of the ranges. The important part is that the value type of the ranges is the same - and here it is, so that's totally fine.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 1
    Why isn't it in the std ranges too? – Pirulax Aug 06 '22 at 19:40
  • Probably just time limitations. I expect the concatenation of different ranges can get quite complicated depending on which types of access/iteration they support. Implementing a working version is quite different from a formally correct definition that can then be implemented performantly. – Ramon Sep 04 '22 at 16:04
  • 2
    I don't see a views::concat() in the standard neither in C++20 nor in C++23. Is this a major missing feature or is there another easy way to achieve this ? – Ludovic Aubert Oct 24 '22 at 14:39
  • Seems like this is planned for C++26 https://github.com/cplusplus/papers/issues/1204 – oblivioncth Jun 06 '23 at 05:28
2

There is actually a concat() in the standard coming with C++23 2/3. Check out the spec: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2214r0.html

Ludovic Aubert
  • 9,534
  • 4
  • 16
  • 28
  • 1
    Good to see plans for it to be added. It's worth noting that the current C++23 draft (N4928) does not yet contain a concat (it would be a range factory in 26.6 if it were there). – ReinstateMonica3167040 Jan 27 '23 at 19:12