【问题标题】:TMP: how to generalize a Cartesian Product of Vectors?TMP:如何推广向量的笛卡尔积?
【发布时间】:2012-11-28 13:52:24
【问题描述】:

Cartesian Product of a vector of integer vectors 有一个出色的 C++ 解决方案(实际上有 2 个解决方案:递归和非递归)。为了说明/简单起见,让我们只关注非递归版本

我的问题是,如何用模板泛化这段代码以获取如下所示的齐次向量 std::tuple

{{2,5,9},{"foo","bar"}}

并生成tuple的齐次向量

{{2,"foo"},{2,"bar"},{5,"foo"},{5,"bar"},{9,"foo"},{9,"bar"}}

如果它让生活更轻松,让我们假设输入中的内部向量都是齐次的。所以像这样的输入是不允许的{{5,"baz"}{'c',-2}}

EDIT将输入从锯齿状向量更改为元组

【问题讨论】:

  • 这应该是可行的。创建size_tindex<size> 类型(基本上是size_t 的n 元组)。创建一个序列模板类型,其中包含 0 到 #vectors-1 的值。创建一个模板来推断返回的元组的类型。创建一个递归函数,该函数遍历返回的叉积中的每个索引(传入一个函数以生成给定深度的最大索引)。使用 seq 对indexvectortuple 上的get()s 进行索引,并将调用包装在()... 中,直接构造生成的tuple 元素。那么鲍勃是你的叔叔。
  • 我写了大约一半,但要睡觉了。 :) 这是使用序列展开get 调用的基本技术:stackoverflow.com/questions/13447063/…,这里是一堆可能包含有用内容的非工作代码:ideone.com/reaDYi

标签: c++ algorithm data-structures c++11 template-meta-programming


【解决方案1】:

更简单的递归解决方案。它将向量作为函数参数,而不是元组。此版本不构建临时元组,而是使用 lambdas。现在它不再进行不必要的复制/移动,并且似乎得到了成功的优化。

#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";
    }
}

【讨论】:

  • +1 得到一个漂亮、干净的答案 - 所以,如果我还有一个 fs(用于浮点数)、一个 cs(用于字符)和一个 ds(用于双精度数),我应该由递归调用cross(),对吗?
  • @kfmfe04 使用更多参数调用cross 就足够了。
  • 完美 - 我需要深入研究您的代码以更好地理解它 - 我确信我可以在其中使用很多技术。感谢您花时间解决这个问题。
  • @zch 将prefout 的类型解耦,将make_tuple 替换为tie 用魔术引用迭代for(auto&amp;&amp; he:h),我认为你会消除大量冗余副本.
  • @Yakk,我的做法略有不同,使用 lambda,但不再有多余的副本。我更喜欢新版本。
【解决方案2】:

我已经有一段时间没有这样做了,但这是第一次尝试。毫无疑问,它可以改进。

template<unsigned fixedIndex, class T>
class DynamicTupleGetter
{
    typedef typename std::tuple_element<fixedIndex, T>::type RetType;
public:
    static RetType get(unsigned dynIndex, const T& tupleInstance)
    {
        const RetType& ret = std::get<fixedIndex>(tupleInstance);

        if (fixedIndex == dynIndex)
            return ret;
        return DynamicTupleGetter<fixedIndex - 1, T>::get(dynIndex, tupleInstance);
    }

};

template<class T>
class DynamicTupleGetter<0, T>
{
    typedef typename std::tuple_element<0, T>::type RetType;
public:
    static RetType get(unsigned dynIndex, const T& tupleInstance)
    {
        assert(dynIndex == 0);
        return std::get<0>(tupleInstance);
    }
};
template<class Source>
struct Converter
{
    typedef typename std::tuple_element<0, Source>::type Zeroth;
    typedef typename std::tuple_element<1, Source>::type First;

    static const size_t size0 = std::tuple_size<Zeroth>::value;
    static const size_t size1 = std::tuple_size<First>::value;

    static const size_t  outerProductSize = size0 * size1;

    typedef typename std::tuple_element<0, Zeroth>::type BaseType0;
    typedef typename std::tuple_element<0, First>::type BaseType1;
    typedef typename std::tuple<BaseType0, BaseType1> EntryType;

    typedef std::array<EntryType, outerProductSize> DestinationType;

    DestinationType create(const Source& source)
    {
        Zeroth zeroth = std::get<0>(source);
        First first = std::get<1>(source);
        typedef typename DynamicTupleGetter<size0 -1, Zeroth> ZerothGetter;
        typedef typename DynamicTupleGetter<size1 -1, First> FirstGetter;
        DestinationType result;
        size_t resultIndex = 0;
        for(size_t i = 0; i < size0; ++i)
            for(size_t j = 0; j < size1; ++j)
            {
                std::get<0>(result[resultIndex]) = ZerothGetter::get(i, zeroth) ;        
                std::get<1>(result[resultIndex]) = FirstGetter::get(j, first); 
                ++resultIndex;
            }
            return result;
    }


};


template<class T>
void create(const T& source)
{
    Converter<T> converter;

    Converter<T>::DestinationType result = converter.create(source);

    std::cout << std::get<0>(std::get<3>(result)) << "," << std::get<1>(std::get<3>(result)) << std::endl;
}


auto intPart = std::make_tuple(2,5,9);
auto stringPart = std::make_tuple("foo","bar");
auto source = std::make_tuple(intPart, stringPart);

void f()
{
    create(source);
}

【讨论】:

  • +1 用于工作代码 - 我不得不稍微调整一下才能让它在 gcc 4.7.2 上编译,但它在 OP 中构建并通过了测试。
  • 这段代码是否适用于auto source = std::make_tuple( intPart, stringPart, charPart, floatPart )
猜你喜欢
  • 2017-06-02
  • 1970-01-01
  • 2018-09-28
  • 2015-04-16
  • 2021-05-06
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多