12

是否有一个很好的算法实现来计算 C++ STL 中两个范围的卷积(甚至提升)?即带有原型的东西(两个范围a..b和的卷积c..d):

template< class Iterator >
void convolution(Iterator a, Iterator b, Iterator c, Iterator d);

修改a..b范围

4

2 回答 2

2

是的 std::transform

std::transform(a, b, c, a, Op);

// a b is the the first input range
// c   is the start of the second range (which must be at least as large as (b-a)
// 
// We then use a as the output iterator as well.

// Op is a BinaryFunction

要在评论中回答有关如何执行状态累积的评论:

struct Operator
{
    State& state;
    Operator(Sate& state) : state(state) {}
    Type operator()(TypeR1 const& r1Value, TypeR2 const& r2Value) const
    {
        Plop(state, r1Value, r2Value);
        return Convolute(state, r2Value, r2Value);
    }
};
State  theState  = 0;
Operator Op(theState);
于 2012-11-16T06:56:44.543 回答
2

我不太确定从两个序列到这两个序列之一的“卷积”应该是什么:这似乎与我的理解不同。下面是使用可变数量的迭代器的卷积版本。因为我现在实在是太懒了,所以我将使用一个不常见的概念,将目标迭代器作为第一个参数而不是最后一个参数传递。这是相应zip()算法的实现:

#include <tuple>

namespace algo
{
    template <typename... T>
    void dummy(T...)
    {
    }

    template <typename To, typename InIt, typename... It>
    To zip(To to, InIt it, InIt end, It... its)
    {
        for (; it != end; ++it, ++to) {
            *to = std::make_tuple(*it, *its...);
            algo::dummy(++its...);
        }
        return to;
    }
}    

下面是一个简单的测试程序,我用来验证上面的内容是否符合我的预期:

#include <deque>
#include <iostream>
#include <iterator>
#include <list>
#include <vector>

enum class e { a = 'a', b = 'b', c = 'c' };

std::ostream& operator<< (std::ostream& out,
                          std::tuple<int, double, e> const& v)
{
    return out << "["
               << std::get<0>(v) << ", "
               << std::get<1>(v) << ", "
               << char(std::get<2>(v)) << "]";
}

int main()
{
    typedef std::tuple<int, double, e> tuple;
    std::vector<int>   v{ 1, 2, 3 };
    std::deque<double> d{ 1.1, 2.2, 3.3 };
    std::list<e>       l{ e::a, e::b, e::c };
    std::vector<tuple> r;

    algo::zip(std::back_inserter(r), v.begin(), v.end(), d.begin(), l.begin());

    std::copy(r.begin(), r.end(),
              std::ostream_iterator<tuple>(std::cout, "\n"));
}                                        
于 2012-11-17T01:27:27.693 回答