Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `std::min` as an algorithm parameter

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:

  1. Is there any proper way to solve the problem in question? i.e. without introducing new vague constructs/writing more than a couple of lines of code.
  2. Is it correct to assume that this became a problem in C++11, after initializer_list overload of min was introduced? So C++11 broke the code that relied on explicitly instantiated std::min?

Thank you!

like image 996
Ap31 Avatar asked Jun 04 '17 11:06

Ap31


1 Answers

Wrap it in a lambda:

std::partial_sum(v.begin(), v.end(), v.begin(), [](auto& a, auto& b) {     return std::min(a, b); }); 
like image 97
yuri kilochek Avatar answered Oct 11 '22 17:10

yuri kilochek