小编典典
更简单的递归解决方案。它使用向量作为函数参数,而不是元组。此版本不构建临时元组,而是使用lambda。现在,它不会进行不必要的复制/移动,并且似乎已成功优化。
#include
#include
// cross_imp(f, v...) means "do `f` for each element of cartesian product of v..."
template
inline void cross_imp(F f) {
f();
}
template
inline void cross_imp(F f, std::vector const& h,
std::vector const&... t) {
for(H const& he: h)
cross_imp([&](Ts const&... ts){
f(he, ts...);
}, t...);
}
template
std::vector<:tuple>> cross(std::vector const&... in) {
std::vector<:tuple>> res;
cross_imp([&](Ts const&... ts){
res.emplace_back(ts...);
}, in...);
return res;
}
#include
int main() {
std::vector is = {2,5,9};
std::vector cps = {"foo","bar"};
std::vector ds = {1.5, 3.14, 2.71};
auto res = cross(is, cps, ds);
for(auto& a: res) {
std::cout << '{' << std::get<0>(a) << ',' <<
std::get<1>(a) << ',' <<
std::get<2>(a) << "}\n";
}
}
2020-07-28