Standard deviation in one pass in C++
In your example, you have two passes over the list - std::distance works in linear time unless it operates on random access iterators.

A naive way to fix this is to calculate the number of elements inside your for loop and check it afterwards. But this way you'll pessimize performance for random access iterators.

To avoid this pessimization you can examine the iterator_tag of you Iter at compile time and decide whether you're going to call std::distance or count your elements in a loop.

The simplest way to do this is in C++14 is by tag dispatching. Here is an example:

template&lt;typename RandomAccessIter&gt;
double sd(RandomAccessIter begin, RandomAccessIter end, std::random_access_iterator_tag)
{
    // calling std::distance
}

template&lt;typename ForwardIter&gt;
double sd(ForwardIter begin, ForwardIter end, std::forward_iterator_tag)
{
    // counting elements in a loop
}

template&lt;typename Iter&gt;
double sd(Iter begin, Iter end)
{
    // dispatching
    return sd(begin, end, typename std::iterator_traits&lt;Iter&gt;::iterator_category());
}


This code will corretly handle bidirectional iterators as well since std::bidirectional_iterator_tag inherits from std::forward_iterator_tag. And code duplication can be avoided by incaplusating common logic in separate functions.

Viola! Now you have only one pass.