I\'m currently working on a problem that requires the random selection of an element from a set. Each of the elements has a weight(selection probability) associated with it.
Assuming that the element weights are fixed, you can work with precomputed sums. This is like working with the cumulative probability function directly, rather than the density function.
The lookup can then be implemented as a binary search, and hence be log(N) in the number of elements.
A binary search obviously requires random_access to the container of the weights.
Alternatively, use a std::map<> and the upper_bound() method.
#include
#include