[英]Weighted addition in 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)
非常感謝...
傳統的方式是有狀態的仿函數。 這些天我們可以用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;
}
(注意:這段代碼都沒有看過編譯器。請注意錯誤)。
非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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.