Is it possible to use std::accumulate with std::min?

前端 未结 1 863
眼角桃花
眼角桃花 2021-02-02 12:09

I am trying to combine std::accumulate with std::min. Something like this (won\'t compile):

vector V{2,1,3};   
cout <&l         


        
相关标签:
1条回答
  • 2021-02-02 12:50

    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);
    }
    
    0 讨论(0)
提交回复
热议问题