我正在尝试将std::accumulate
和std::min
结合起来。类似这样的代码(不会编译):
vector<int> V{2,1,3};
cout << accumulate(V.begin()+1, V.end(), V.front(), std::min<int>);
有可能吗?是否可以不为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);}
);
我知道有std::min_element
。我不是在尝试寻找最小元素,我需要将std::accumulate
和std::min
(或::min
)组合在我的库中,这样就可以像C++中的表达式一样进行函数编程。
发布于 2012-07-24 15:59:24
问题是有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);
因此,您的代码是不明确的,编译器不知道选择哪个重载。您可以通过使用中间函数指针来声明您想要的是哪一个:
#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);
}
https://stackoverflow.com/questions/11626304
复制相似问题