Should I call a method (i.e. size()) multiple times or store it (if I know the value will not change) I have a function that searches the shortest vector in a vector of vectors of pointers.

Which is a better way?

std::vector&lt;std::vector&lt;void*&gt;&gt; const&amp; ways

{
   size_t i = SIZE_MAX;
   for(auto&amp; it : ways)
   {
      if(i &gt; it.size())
         i = it.size();
   }
}


OR

std::vector&lt;std::vector&lt;void*&gt;&gt; const&amp; ways

{
   size_t i = SIZE_MAX;
   for(auto&amp; it : ways)
   {
      const auto temp = it.size();
      if(i &gt; temp)
         i = temp;
   }
}


As far as I can see size() does not return reference so second one is a better way, is it true?

Also, is there any other approach you can suggest for this method?
Calling size() twice, like you are, almost definitely get's optimized out in any modern compiler. How you are doing it is perfectly fine. You could also do it with std::max_element...

auto max = std::max_element(ways.begin(), ways.end(), 
    [](const std::vector&lt;void*&gt;&amp; left, const std::vector&lt;void*&gt;&amp; right)
    { 
        return left.size() &lt; right.size(); 
    })-&gt;size();


Or maybe you write the lambda as a functor instead and a little more generic, like:

struct ContainerSizeComparer
{
    template&lt;typename Container&gt;
    bool operator()(const Container&amp; left, const Container&amp; right)
    {
        return left.size() &lt; right.size();
    }
};

auto max = std::max_element(ways.begin(), ways.end(), ContainerSizeComparer())-&gt;size();


This is one of those interesting times when hand rolling the loop is actually more readable and as small as using standard algorithms though. Unless you have a reason to write ContainerSizeComparer and use it in multiple places I would personally stick with what you were doing.