用STD方法对两个级数求和



我有两个相同大小的std::vector<double>,它们代表不同的系列。

有没有一种干净的方法来用STD求和这些向量?

类似于std::accumulate,但在两个系列上工作

以下是两个答案,取决于输出是否应该是向量的和,还是它们的标量和(在这种情况下,我不确定为什么它们长度相等是相关的)。

矢量和

二进制版本的std::transform:

std::vector<double> res(lhs.size());
std::transform(
     lhs.begin(), lhs.end(),
     rhs.begin(),
     res.begin(),
     [](double l, double r){return l + r;});

注意,您可以使用functional中的std::plus<double>()而不是lambda。

标量和

auto sum = std::accumulate(std::begin(lhs), std::end(lhs), 0.0) + 
     std::accumulate(std::begin(rhs), std::end(rhs), 0.0);

或使用boost::range::join:

auto both = boost::range::join(lhs, rhs);
auto sum = std::accumulate(std::begin(both), std::end(both), 0.0);

我强烈建议只使用两个accumulate s并添加结果。

如果你真的坚持,因为你的向量长度相同,你可以滥用std::inner_product:

double result = std::inner_product(veca.begin(), veca.end(), vecb.begin(),
                                   0.0, std::plus<double>(), std::plus<double>());

我会保持简单,只调用两次accumulate,您可以将它添加到一个单独的函数中,该函数为您处理它。它更具可读性,每个人都能第一眼理解它。

namespace util{
  double accumulate(std::vector<double>& a, std::vector<double>& b)
  {
    return std::accumulate(a.begin(), a.end(), 0.) + std::accumulate(b.begin(), b.end(), 0.);
  }
}

最新更新