【问题标题】:discrete_distrubution of struct结构的离散分布
【发布时间】:2015-10-31 19:17:31
【问题描述】:

我有一个vector 的真实值:

vector<double> values;

还有一个discrete_distribution

discrete_distribution<size_t> dis(values.begin(), values.end());

但现在我需要将double 值的向量变成结构向量:

struct Data
{
   double value;
   int index;
};

vector<Data> values;

如何在不将值复制到单独的vector 的情况下构建相应的discrete_distribution

【问题讨论】:

  • discrete_distribution 中的模板参数必须是整数。
  • @101010 你的意思是像int,为什么?
  • 有一个有效类型列表,size_t 不是其中之一。也就是说,在几乎所有平台上,size_t 是一种受支持类型的 typedef,但这并不能使代码严格正确。 en.cppreference.com/w/cpp/numeric/random/discrete_distribution

标签: c++ c++11


【解决方案1】:

看来你可以使用下面的重载(number 4

template< class UnaryOperation >
discrete_distribution(std::size_t count, double xmin, double xmax,
                      UnaryOperation unary_op);

像这样。

std::discrete_distribution<int>
make_distribution(const std::vector<Data>& weights)
{
  const auto n = weights.size();
  const auto op = [&weights](double d){
    const auto index = static_cast<std::size_t>(d - 0.5);
    //std::cout << "weights[" << index << "].value == " << weights[index].value << "\n";
    return weights[index].value;
  };
  return std::discrete_distribution<int> {n, 0.0, static_cast<double>(n), op};
}

它应该可以工作,但它是一个kludge。

【讨论】:

  • 请写出你将如何实例化一个离散分布对象,考虑到 N=100 个值,该值在 [0, 1] 范围内。
  • @Nick 对不起,我最初的想法是不正确的。请查看更新答案。
  • 你能解释一下分配给索引的值吗?
  • @Nick 该公式在文档中,可以在我的答案中给出的链接中找到。如果你输入这些数字,它恰好会生成一个序列0.5, 1.5, …, n - 0.5。减去0.5,你会得到索引。
【解决方案2】:

Boost 有一个transform_iterator 可以转换迭代器的返回值:

const double get_value(const Data & d)  { return d.value; }


auto beg = boost::make_transform_iterator(values.begin(), get_value);
auto end = boost::make_transform_iterator(values.end(), get_value);
discrete_distribution<size_t> dis(beg, end);

(基于this answer

【讨论】:

  • 我不能使用 boost。如何仅使用 std 库获得相同的结果?
猜你喜欢
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
  • 2020-05-05
  • 2021-11-02
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多