c ++中的加权加法

时间:2017-03-16 14:58:04

标签: c++

按元素逐个添加两个数组并将结果保存到第一个数组可以通过以下代码实现(用c ++ 14编译):

#include <algorithm>
#include <iostream>
#include <array>

int main()
{
    std::array<double,3> a = {1, 2, 3};
    std::array<double,3> b = {4, 5, 6};
    std::transform(a.begin( ), a.end( ), b.begin( ), a.begin( ),std::plus<double>( ));

    for(double d : a)
        std::cout << d << std::endl;

    return 0;
}

那是

a[i] = a[i] + b[i]

如果我想获得以下内容怎么办?是否仍然可以通过std :: transform或std算法中的任何其他功能来完成?

a[i] = a[i] * weight + b[i] * (1. - weight)

非常感谢...

2 个答案:

答案 0 :(得分:7)

传统的方式是有状态的仿函数。这些天我们可以用lambda:

来做
#include <algorithm>
#include <iostream>
#include <array>

int main()
{
    std::array<double,3> a = {1, 2, 3};
    std::array<double,3> b = {4, 5, 6};
    const double weight = 0.7;

    std::transform(a.begin( ), a.end( ), b.begin( ), a.begin( ),
             [weight](double aa, double bb) {
                 return aa*weight + bb*(1. - weight);
             }
    );

    for(double d : a)
        std::cout << d << std::endl;

    return 0;
}

按要求,旧方式:

#include <algorithm>
#include <iostream>
#include <array>

struct weighted_add {
    const double weight;
    double operator() const (double aa, double bb) {
        return aa*weight + bb*(1.-weight);
    }
    weighted_add(double weight_) : weight(weight_) {}
};

int main()
{
    std::array<double,3> a = {1, 2, 3};
    std::array<double,3> b = {4, 5, 6};

    std::transform(a.begin( ), a.end( ), b.begin( ), a.begin( ), weighted_add(0.7));

    for(double d : a)
        std::cout << d << std::endl;

    return 0;
}

(注意:这些代码都没有看过编译器。请注意错误。)

答案 1 :(得分:3)

非lambda解决方案(与C ++ 03兼容)将是:

#include <algorithm>
#include <iostream>
#include <array>

struct MyFunctor
{
    const double _weight;
    MyFunctor(double weight) : _weight(weight) {}
    double operator()(double a, double b) const
    {
        return a * _weight + b * (1. - _weight);
    }
};

int main()
{
    std::array<double,3> a = {1, 2, 3};
    std::array<double,3> b = {4, 5, 6};
    double weight = 0.7;
    std::transform(a.begin( ), a.end( ), b.begin( ), a.begin( ), MyFunctor(weight));

    for(double d : a)
        std::cout << d << std::endl;

    return 0;
}