Is it possible to use std::accumulate with std::mi

2019-03-17 21:51发布

I am trying to combine std::accumulate with std::min. Something like this (won't compile):

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

Is it possible? Is it possible to do without writing wrapper functor for std::min?
I know that I can do this with lambdas:

vector<int> V{2,1,3};   
cout << std::accumulate(
    V.begin()+1, V.end(),
    V.front(), 
    [](int a,int b){ return min(a,b);}
);

And I know there is std::min_element. I am not trying to find min element, I need to combine std::accumulate with std::min (or ::min) for my library which allows function-programming like expressions in C++.

2条回答
Fickle 薄情
2楼-- · 2019-03-17 22:07

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);
}
查看更多
Animai°情兽
3楼-- · 2019-03-17 22:07

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;
}
查看更多
登录 后发表回答