I wrote a RandIt class (code below) that acts like an iterator, but returns random integers when dereferenced. The main use case is to initialize a vector with random data, as in
std::vector<int> v(RandIt<0,99>{}, RandIt<0,99>{50});
to generate 50 numbers between 0 and 99.
typedef RandIt::iterator_category - std::random_access_iterator_tag because
- it must be at least ForwardIterator for the vector constructor in order to allocate the right amount of space for the assembly using
std::distance . Otherwise, emplace_back used, with redistribution and copying. - it should be RandomAccessIterator for
std::distance for constant time, instead of incrementing and testing in a loop.
However, this is a lie, since RandIt dereferencing returns an int value by value, and ForwardIterators are best needed to return a reference to an object in memory.
(This could also be a lie due to the rejection of the ForwardIterator multi-pass guarantee: repeating the sequence will again give different results. But cppreference gives a “formal” version
expression (void)++It(a), *a equivalent to *a
which seems to be true for certain "equivalent" values.)
So I definitely break the rules by saying that I'm not like that. However, this seems to work.
Does it bite me? What are the potential consequences of lying about it?
#include <random>
Take a look at Coliru .
source share