Suppose (this is just an example) I want to use ranges-v3 library in order to create a sequence such as this one:
2 3 7 20 30 70 200 300 700 2000 3000 7000 ...
Basically for every i
I've obtained from iota(0)
I want to insert a sequence 2*10^i, 3*10^i, 7*10^i
into the pipeline for further processing:
#include <cmath>
#include <iostream>
#include <range/v3/all.hpp>
int main(){
using namespace ranges::views;
auto rng = iota(0) |
/*
insert 2*10^i, 3*10^i, 7*10^i
*/ |
take_while([](int x){ return x < 10000;});
for(auto i: rng) {
std::cout << i << " ";
}
std::cout << "\n";
}
I'm not sure how to implement that properly. I managed to create a working example by returning temporary containers, as described in this answer:
#include <cmath>
#include <iostream>
#include <range/v3/all.hpp>
int main(){
using namespace ranges::views;
auto rng = iota(0) |
transform([](int i) {
int mul = pow(10, i);
return std::array{2*mul, 3*mul, 7*mul};
}) |
cache1 |
join |
take_while([](int x){ return x < 10000;});
for(auto i: rng) {
std::cout << i << " ";
}
std::cout << "\n";
}
But I wonder if I can do it more directly. In fact, ranges::views::for_each
sounds like a good fit there (because it flattens returned range automatically) but I'm not sure what to return from it:
auto rng = iota(0) |
for_each([](int i){
int mul = pow(10, i);
return /* ?????????????????????????? */
}) |
take_while([](int x){ return x < 10000;});
Or perhaps there is more idiomatic way to insert custom elements inside the pipeline?