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

Viewed 4335

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

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

Is it possible? Is it possible to do without writing wrapper functor for std::min?
I know that I can do this with 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);}
);

And I know there is std::min_element. I am not trying to find min element, I need to combine std::accumulate with std::min (or ::min) for my library which allows function-programming like expressions in C++.

2 Answers

From C++20 you can use std::ranges::min

#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
#include <climits>

int main() {
    std::vector<int> v{1,2,3,47,5};
    std::cout << std::accumulate(v.begin(), v.end(), INT_MAX, std::ranges::min) << std::endl; 
    std::cout << std::accumulate(v.begin(), v.end(), INT_MIN, std::ranges::max) << std::endl; 
}

1
47

Note that there is no std::ranges::accumulate, as it was not done for C++20.

Related