C++11 Generating random numbers from frequently changing range

有些话、适合烂在心里 提交于 2019-12-01 17:05:58

I would do

int getIntFromRange1(int from, int to){
    std::uniform_int_distribution<int> dist(from, to);
    return dist(mt);
}
manlio

I would do as in Jarod42's answer: distribution objects should be lightweight, so constructing a new distribution when you need a random number is simple and fast (it's the random engine that is expensive).

However you can also consider this implementation:

inline int get_int_from_range(int from, int to)
{
  using distribution_type = std::uniform_int_distribution<int>;
  using param_type = typename distribution_type::param_type;

  thread_local distribution_type dist;
  return dist(mt, param_type(from, to));
}

The rationale is that there could be distributions that need to store values/states.

This isn't probably the case for integers and uniform distribution, but it's interesting that in N4316 - std::rand replacement the proposed implementation uses this technique.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!