微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 C++ 离散分布,权重取自数据结构

如何解决使用 C++ 离散分布,权重取自数据结构

我正在尝试使用 discrete distribution (here too。但是,正如您在示例中看到的那样,您可以通过编写:

std::discrete_distribution<int> distribution {2,2,1,2};

 std::discrete_distribution<> d({40,10,40});

如果你有 10 或 4 个带权重的元素,这很好。 (也不知道括号有没有必要)

但我想将它用于 1000 个元素。 我在结构向量中有这些元素,例如:

struct Particle{
   double weight;
};

std::vector<Particle> particles;

正如你所看到的,这个向量的每个元素都有一个权重。我想用这个权重来初始化离散分布。

我可以用一个很长的句子一个一个地写,但我认为不是这样。 如何将向量的权重放在离散分布的声明中?

解决方法

您可以将所有权重放入 std::vector<double> weights;,然后您可以将离散分布初始化为 std::discrete_distribution<> distr(weights.begin(),weights.end());。代码:

std::vector<double> weights;
for (auto const & p: particles)
    weights.push_back(p.weight);
std::discrete_distribution<> distr(weights.begin(),weights.end());

完整的工作示例代码:

Try it online!

#include <random>
#include <vector>
#include <iostream>

int main() {
    struct Particle {
        double weight = 0;
    };
    std::vector<Particle> particles({{1},{2},{3},{4}});
    std::vector<double> weights;
    for (auto const & p: particles)
        weights.push_back(p.weight);
    std::discrete_distribution<size_t> distr(weights.begin(),weights.end());
    std::random_device rd;
    for (size_t i = 0; i < 20; ++i)
        std::cout << distr(rd) << " ";
}

输出:

1 3 3 3 2 0 2 1 3 2 3 2 2 1 1 3 1 0 3 1 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。