So I ran into this problem: I need to replace every element of the std::vector<int>
with the minimum of whatever came before it (inclusive).
Naturally std::partial_sum
comes to mind - if I could pass std::min
as the BinaryOp
, it would do the job.
Well turns out I can't do that because std::min<int>
is an overloaded function - it works for both int
and initializer_list<int>
and partial_sum
template can't be instantiated with the unknown type.
Usually this is resolved by having a class with a templated operator()
, like std::plus<void>
etc, but standard library doesn't seem to have one for min
and max
.
I feel like I either have to implement my own T min<T>(T,T)
, which will be an exact clone of std::min
with the exception of not having an initializer_list
overload, or to implement my own class min
akin to std::plus
. Both feel kinda wrong because one would expect standard library to have such a basic thing, and also basic things are often tricky to implement:)
So here are my questions:
initializer_list
overload of min
was introduced? So C++11 broke the code that relied on explicitly instantiated std::min
?Thank you!
Wrap it in a lambda:
std::partial_sum(v.begin(), v.end(), v.begin(), [](auto& a, auto& b) { return std::min(a, b); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With