c ++累积了聚合值和原始值

时间:2017-12-08 20:05:40

标签: c++ reduce higher-order-functions accumulate

我有一个用例,我希望在遍历数组时累积sum变量,并对每两个邻居执行二进制操作。我想起了accumulate又名reduce。但我发现自己在写这个

  int sum = 0;
  auto result = // this result is discarded. its always the last element value
      accumulate(v.begin() + 1, v.end(), *v.begin(),
                 [&sum, &duration](int left, int right) {
                   sum += min(right - left, duration);
                   return right; // only care about the side effect in the lambda
                 });

我认为这很难看,但我找不到消除用于跟踪聚合值的额外变量和的方法。我所做的就等于这个传统的循环。

  for (vector<int>::size_type i = 1; i < v.size(); i++) {
    sum += min(v[i] - v[i - 1], duration);
  }

有没有办法我不能使用int sum并只从reduce函数返回所需的总和?

一些预期的结果

// second param is the "duration" but its not important. 
vector<int> v{1, 2, 3};
REQUIRE(foo(v, 3) == 5);
vector<int> v1{1, 2, 3};
REQUIRE(foo(v1, 1) == 3);
vector<int> v2{1, 5, 7};
REQUIRE(foo(v2, 2) == 6);

0 个答案:

没有答案