Is it possible to use std::accumulate with std::min?

只愿长相守 提交于 2019-12-03 01:36:11

The problem is that there are several overloads of the min function:

template <class T> const T& min(const T& a, const T& b);

template <class T, class BinaryPredicate>
const T& min(const T& a, const T& b, BinaryPredicate comp);

Therefore, your code is ambiguous, the compiler does not know which overload to choose. You can state which one you want by using an intermediate function pointer:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> V{2,1,3};
  int const & (*min) (int const &, int const &) = std::min<int>;
  std::cout << std::accumulate(V.begin() + 1, V.end(), V.front(), min);
}

Very old question, but may help some one else :) Find minimum accumulating sum.

C++14:

/*
Find the minimum accumulate sum.

input
4
4 -66 0 -11

output
-73

Explanation:
First sum == 4, minimum = 4
then, sum ==
  4 + -66 = -62, minimum == -62
  -62 + 0 = -62, minimum == -62
  -62 + -11 = -73, minimum == -73
*/
#include <bits/stdc++.h>

using namespace std;

typedef vector<int> vi;

const int INF = 1e9;


int main(){
  int n;
  cin >> n;

  vi v;
  for (int i = 0 ; i < n ; ++i){
    int x;
    cin >> x;
    v.push_back(x);
  }

  int min_sum = v.front();
  accumulate(v.begin() + 1, v.end(), min_sum,
              [&min_sum](auto &x1, auto &x2){
                min_sum = min(min_sum, x1 + x2);
                return x1 + x2;
              });
  cout << "Minimum is: " << min_sum << '\n';

  return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!