是否可以使用std :: accumulate与std :: min? [英] Is it possible to use std::accumulate with std::min?

查看:248
本文介绍了是否可以使用std :: accumulate与std :: min?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 std :: accumulate std :: min 结合。这样的东西(不会编译):

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>);

有可能吗?
是否可以不为 std :: min ?编写包装器函数?

我知道我可以用lambdas: / p>

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);}
);

我知道有 std :: min_element 。我不是想找到min元素,我需要结合 std :: accumulate std :: min (或 :: min )。

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++.

推荐答案

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);
}

这篇关于是否可以使用std :: accumulate与std :: min?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆