Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 543
ephemerr Avatar asked Nov 01 '25 02:11

ephemerr


1 Answers

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

like image 154
康桓瑋 Avatar answered Nov 02 '25 16:11

康桓瑋