2012-07-24 125 views
18

我正在尝试将std::accumulatestd::min结合使用。像这样的东西(不会编译):是否有可能使用std :: accumulate和std :: min?

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

这可能吗? 有没有可能为std::min写包装仿函数?
我知道,我可以用lambda表达式做到这一点:

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::accumulatestd::min(或::min)结合起来用于我的库,该库允许在C++中使用函数式编程(如表达式)。

回答

19

的问题是,有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); 
} 
+2

你可以使用一个丑陋投过'(const int的&(*)(const int的&,const int的&))的std ::分钟'。 – 2012-07-24 08:07:25

+3

我倾向于更喜欢lambda版本。 – moooeeeep 2012-07-24 08:07:51

+4

@JesseGood:你没有'static_cast'? :\ – Mehrdad 2012-07-24 08:08:04

相关问题