How to make join view in C++ preserving random access?

How to make join view in C++ preserving random access?
typescript
Ethan Jackson

The code below breaks at last line as joined view v isn't a random access range.

vector<string> v0 = {"word","good","best","good"}; auto it = v0.begin() + 1; auto r1 = ranges::subrange(v0.begin(), it); auto r2 = ranges::subrange(it + 1, v0.end()); auto rr = {r1,r2}; auto v = views::join(rr); auto w1 = v.begin() + 1;

r1 and r2 keep this quality. Is it possible to join two subranges, preserving random access? Is there any workaround? Basically, I need a view of a vector with a specific element excluded, with the random accessible result.

Answer

In c++26 you can use views::concat which supports random access:

auto r1 = std::ranges::subrange(v0.begin(), it); auto r2 = std::ranges::subrange(it + 1, v0.end()); auto v = std::views::concat(r1, r2); auto w1 = v.begin() + 1; std::println("{}", *w1); // print best std::println("{}", v[1]); // print best

Demo

Related Articles