Let us say I've got a collection of items and a score function on them:
struct Item { /* some data */ };
std::vector<Item> items;
double score(Item);
I'd like to find the item from that collection whose score is the lowest. An easy way to write this is:
const auto argmin = std::min_element(begin(items), end(items), [](Item a, Item b) {
return score(a) < score(b);
});
But if score
is a heavy-to-compute function, the fact that std::min_element
actually calls it multiple times on some items may be worrying. And this is expected because the compiler cannot guess score
is a pure function.
How could I find argmin
but with score
being called only once per item? Memoization is one possibility, anything else?
My objective is to write a code snippet which is easy to read, in a dream world as obvious as calling std::min_element
on the collection is.