如何在C++中以不同概率从数组中随机选取元素

Mic*_*ael 4 c++ random sampling

假设我有vector<Point> p一些对象。

我可以简单地选择一个均匀随机的p[rand() % p.size()]

现在假设我有另一个相同大小的 doubles 向量vector <double> chances

我想从 p 中随机采样,每个元素的概率与其值类似chances(总和可能不等于 1.0)。我怎样才能在 C++ 中实现这一点?

Qui*_*mby 11

您正在寻找std::discrete_distribution. 把...忘了吧rand()

#include <random>
#include <vector>

struct Point {};

int main() {
    std::mt19937 gen(std::random_device{}());

    std::vector<double> chances{1.0, 2.0, 3.0};
    // Initialize to same length.
    std::vector<Point> points(chances.size());
    // size_t is suitable for indexing.
    std::discrete_distribution<std::size_t> d{chances.begin(), chances.end()};

    auto sampled_value = points[d(gen)];
}
Run Code Online (Sandbox Code Playgroud)

为了方便起见,权重之和不必为 1。