Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can ranges min recalculations be avoided

Goal is to minimize a function over a range of input values. Performance matters.
Unfortunately, the ranges::min() algorithm recomputes the output for the live optimum over and over again.

It seems like the algorithm could cache the output value corresponding to the optimum, or am I missing something ?

In this example, why does f(x=0) need to be called n times ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to call ranges::min() in a more optimized way ?

#include <ranges>
#include <algorithm>
#include <stdio.h>
using namespace std;

int main()
{
    auto f=[](int x){
        printf("calling f(x=%d)\n", x);
        return x*x;
    };
    auto rg = views::iota(0,4);
    int x1 = ranges::min(rg, {}, f);
}

enter image description here

>Solution :

Can ranges::min be implemented in a fashion such that it stores the projected object that it is currently testing against? Well, that would impose specific requirements on such an item. Namely, that you can overwrite it (if you find a smaller element, so that you can cache it in the same variable).

This is not currently a requirement of projection; the result simply has to be comparable with the comparison function. So to impose that would effectively make projection more strict.

Now, an implementation is allowed to cache the value if it so chooses, as projection functors are required to be pure. That is, if it detects that the value type from the projection is copyable, it can copy it. But that’s a matter of quality of implementation, not a standard requirement.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading