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