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
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)
| 归档时间: |
|
| 查看次数: |
3083 次 |
| 最近记录: |