TMP:如何概括向量的笛卡尔积?笛卡尔、向量、TMP

2023-09-10 22:44:32 作者:初晴夜雨

有一个优秀的C ++解决方案(实际上2解决方案:递归和非递归),在 笛卡尔乘积整数向量的载体 。为了便于说明/简单起见,我们只专注于在非递归版本

There is an excellent C++ solution (actually 2 solutions: a recursive and a non-recursive), to a Cartesian Product of a vector of integer vectors. For purposes of illustration/simplicity, let us just focus on the non-recursive version.

我的问题是,人们如何能概括这个code使用模板采取的std ::元组齐载体,看起来像这样:

My question is, how can one generalize this code with templates to take a std::tuple of homogeneous vectors that looks like this:

{{2,5,9},{富,酒吧}}

和生成的均匀矢量元组

{{2,富},{2,吧},{5,富},{5,酒吧},{9,富}, {9,酒吧}}

如果它使生活变得更容易,让我们假设输入内部的每个vector都是均匀的。所以像这样的投入是不允许: {{5,巴兹} {'C', - 2}}

If it makes life any easier, let us assume that the internal vectors in the input are each homogeneous. So inputs like this are not allowed: {{5,"baz"}{'c',-2}}

修改改变转自铁血的矢量输入到一个元组

EDIT changed input from jagged vector to a tuple

推荐答案

简单的递归解决方案。它需要的载体作为函数参数,而不是作为一个元组。此版本不搭建临时元组,而是使用lambda表达式来代替。现在,它是没有不必要的复制/移动,似乎得到成功地进行了优化。

Simpler recursive solution. It takes vectors as function arguments, not as a tuple. This version doesn't build temporary tuples, but uses lambdas instead. Now it makes no unnecessary copies/moves and seems to get optimized successfully.

#include<tuple>
#include<vector>

// cross_imp(f, v...) means "do `f` for each element of cartesian product of v..."
template<typename F>
inline void cross_imp(F f) {
    f();
}
template<typename F, typename H, typename... Ts>
inline void cross_imp(F f, std::vector<H> const& h,
                           std::vector<Ts> const&... t) {
    for(H const& he: h)
        cross_imp([&](Ts const&... ts){
                      f(he, ts...);
                  }, t...);
}

template<typename... Ts>
std::vector<std::tuple<Ts...>> cross(std::vector<Ts> const&... in) {
    std::vector<std::tuple<Ts...>> res;
    cross_imp([&](Ts const&... ts){
                  res.emplace_back(ts...);
              }, in...);
    return res;
}

#include<iostream>

int main() {
    std::vector<int> is = {2,5,9};
    std::vector<char const*> cps = {"foo","bar"};
    std::vector<double> 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";
    }
}