TMP: how to generalize a Cartesian Product of Vectors?

前端 未结 2 1124
时光取名叫无心
时光取名叫无心 2020-11-27 15:57

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 illustrat

2条回答
  •  没有蜡笔的小新
    2020-11-27 16:16

    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
    #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> cross(std::vector const&... in) {
        std::vector> 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";
        }
    }
    

提交回复
热议问题