So imagine i have 2 vectors (for reasons to do with the framework i am working in):
std::vector<bool> valid = {false, true, true, false};
std::vector<int> percentages = {2, 50, 3, 100};
These vectors represent a batteries validity and the percentage charge. I want to find the minimum charge of the valid batteries. To do this with ranges, the best i can come up with is:
auto min = std::get<1>(
std::ranges::min(
std::views::zip(valid, percentages) |
std::views::filter([](const auto& vals) {return std::get<0>(vals);}),
[](const auto& vals0, const auto& vals1) {
return std::get<1>(vals0) < std::get<1>(vals1);
}));
Now this works but it is nearly impossible to read. So the for loop variety would be something like:
int min_percentage = 100;
for (const auto& [is_valid, percentage] : std::views::zip(valid, percentages)) {
if (is_valid) {
min_percentage = std::min(min_percentage, percentage);
}
}
Which works just fine as well.
The second one is objectively better. So the question is, is there a way to write this with ranges whilst keeping the code readable?