是否可以将std :: accumulate与std :: min一起使用?

Leo*_*sky 19 c++ stl accumulate

我想和之std::accumulate合作std::min.像这样的东西(不会编译):

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

可能吗?是否可以不编写包装函数std::min?
我知道我可以用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);}
);
Run Code Online (Sandbox Code Playgroud)

而且我知道有std::min_element.我不是要找到min元素,我需要std::accumulate和我的库结合std::min(或::min),它允许像C++中的表达式一样进行函数编程.

Luc*_*lle 22

问题是该min函数有几个重载:

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);
Run Code Online (Sandbox Code Playgroud)

因此,您的代码含糊不清,编译器不知道选择哪个重载.您可以使用中间函数指针来说明您想要的那个:

#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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我倾向于更喜欢lambda版本. (4认同)
  • @JesseGood:你没有`static_cast`?:\ (4认同)
  • 你也可以使用一个丑陋的演员`(const int&(*)(const int&,const int&))std :: min <int>`. (2认同)