2

When I look at the documentation for std::exponential_distribution, it does not seem to expose a standard way for changing the lambda parameter at runtime.

There is a param method, but it takes the opaque member type param_type, and the only documented way of obtaining an object of this type is to call param with no arguments, but that would imply a different instance must have first been created with that parameter.

Below, I show two non-documented ways of resetting lambda that compile, but I do not know whether they will result in correct behavior at runtime.

#include <random>
#include <new>

int main(){
    std::random_device rd;
    std::mt19937 gen(rd());
    std::exponential_distribution<double> intervalGenerator(5);

    // How do we change lambda after creation?
    // Construct a param_type using an undocumented constructor?
    intervalGenerator.param(std::exponential_distribution<double>::param_type(7));

    // Destroy and recreate the distribution?
    intervalGenerator.~exponential_distribution();
    new (&intervalGenerator) std::exponential_distribution<double>(9);
}

Is there a documented way to do this, and if not, are either of the two solutions safe to use?

4

1 回答 1

5

只需为旧实例分配一个新生成器:

std::exponential_distribution<double> intervalGenerator(5);
intervalGenerator = std::exponential_distribution<double>(7);

便携、易读且明显正确。


还,

intervalGenerator.param(std::exponential_distribution<double>::param_type(7));

如 N3337 和 N4141 中的 26.5.1.6/9 所述,它是安全的,因此您也可以使用它。但是对于第一个变体,一开始就不会出现可移植性问题。

于 2017-04-03T22:19:59.463 回答