4

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.

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is there c++20 solution?
@ephemerr I don't think join_view can make random access in amortized constant time, so nope. What you want to do is basically what views::concat does, so maybe you could use the range/v3 version of that.
@ephemerr Should be quite easy to backport it, especially if you only want to support the random access range. Store begin/end of both ranges in the view, and in the iterator having a reference to view just calculate when you switch from the first to the second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.