std::map::lower_bound
+ partial_sum
+ C++11 lambdas
Here is a generalization where you can easily give a probability for each lambda.
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <random>
#include <vector>
int main() {
typedef std::pair<double, std::function<void()>> P;
auto v = std::vector<P> {
{0.2, [](){std::cout << "a" << std::endl;}},
{0.5, [](){std::cout << "b" << std::endl;}},
{0.3, [](){std::cout << "c" << std::endl;}}
};
std::partial_sum(v.begin(), v.end(), v.begin(),
[](const P& x, const P& y){return P(x.first + y.first, y.second);}
);
auto m = std::map<P::first_type, P::second_type>(v.begin(), v.end());
std::random_device r;
std::mt19937 prng(r());
std::uniform_real_distribution<> dist(0.0, 1.0);
for (auto i = 0u; i < 10u; ++i) {
auto r = dist(prng);
std::cout << r << std::endl;
m.lower_bound(r)->second();
std::cout << std::endl;
}
}
Sample output:
0.255392
b
0.0884198
a
0.8279
c
0.095513
a
0.34819
b
0.20279
b
0.327021
b
0.402535
b
0.64069
b
0.848767
c
Related: How do I select a range of values in a switch statement?