I want to create a view that will have views of both halves of the string. I added some code examples of what I would like to achieve. How could I do it?
#include <iostream>
#include <string>
#include <ranges>
#include <vector>
#include <cassert>
int main() {
std::vector<std::string> data{
"abcdef",
"12345678910",
"ab",
"qwerty",
"xyzxyz",
"987654321"
};
// Ok:
auto chunk3 = std::views::chunk(data, 3);
assert(std::ranges::size(chunk3) == 2);
for (auto chunk : chunk3) {
assert(std::ranges::size(chunk) == 3);
}
// Problem:
auto view = /*...*/
assert(std::ranges::size(view) == 6);
for (auto halves : view) {
assert(std::ranges::size(halves) == 2);
}
}
What does chunk3 look like:
/*
chunk3 {
{"abcdef", "12345678910", "ab"}
{"qwerty", "xyzxyz", "987654321"}
}
*/
What the view would look like:
/*
view {
{{"abc"}, {"def"}}
{{"123456"}, {"78910"}}
// ...
}
*/
CodePudding user response:
You can use views::transform
to convert the original element string
into an array containing two half-string_view
s
auto view = data | std::views::transform([](std::string_view s) {
return std::array{s.substr(0, s.size() / 2),
s.substr(s.size() / 2)};
});