Get a random member of a container It was not obvious how to get a random member of a container. So I wrote a function to retrieve it given a generator.

namesapce ThorsAnvil
{
    namespace Util
    {
        using Distribution = std::uniform_int_distribution&lt;int&gt;;

        /* Get a distribution from [0, max)   */
        /* None maths nerds: Note the [ and ) */
        Distribution getDist(int max)
        {
            return Distribution{0, max - 1};
        }

        template&lt;typename C, typename G&gt;
        auto getRandomIteratorFromContainer(C&amp; container, G&amp; generator)
        {
            auto pos = container.begin();

            int     offset  = getDist(container.size())(generator);
            std::advance(pos, offset);

            return pos;
        }
    }
}
Long name

ThorsAnvil::Util::getRandomIteratorFromContainer is a really long name. I suggest something like getRandomElement or even randomElement.

Unnecessary function

getDist seems kind of unnecessary to me. I think it would be cleaner to construct the distribution directly.

std::uniform_int_distruction&lt;int&gt; dist{0, container.size() - 1};


Types

The integer type used for iterator arithmetic is typename C::difference_type. This is almost always equivalent to std::ptrdiff_t so to be crystal clear, use std::ptrdiff_t.

std::uniform_int_distruction&lt;std::ptrdiff_t&gt; dist{0, container.size() - 1};


Unnecessary variable

offset is initialized with a random offset and is only used once. If it's only used once then it doesn't really need to exist.

std::advance(pos, dist(generator));


Wrong function

std::advance modifies an existing iterator. This means that we need store the iterator, advance it, then return the iterator. That's three steps. std::next takes an iterator and returns an incremented one.

return std::next(container.begin(), dist(generator));


Covering all cases

Using .begin() and .size() is a little bit restrictive. If we use std::begin and std::size, this function will work on C-style arrays which is a nice. If we want to be even more general (as Toby mentioned in the comments), we can let ADL pick up the right function for containers that declare their own begin and size functions.

using std::begin;
using std::size;


Short names

My answer has been pretty nitpicky so far but this is particularly nitpicky. Long template parameter names that clearly describe the parameter are better than single character names.

template &lt;typename Container, typename Generator&gt;


How I would write it

After applying the above transformations. We get this function:

template &lt;typename Container, typename Generator&gt;
auto random_element(Container &amp;con, Generator &amp;gen) {
  using std::begin;
  using std::size;
  std::uniform_int_distribution&lt;std::ptrdiff_t&gt; dist{0, size(con) - 1};
  return std::next(begin(con), dist(gen));
}