c++ - 是否有记录的方法来重置现有 std::exponential_distribution 对象上的 lambda 参数?

标签 c++ c++11 exponential-distribution

当我查看 std::exponential_distribution 的文档时,它似乎没有公开在运行时更改 lambda 参数的标准方法。

有一个 param 方法,但它采用不透明成员类型 param_type,并且获取此类型对象的唯一记录方法是调用 param 不带任何参数,但这意味着必须首先使用该参数创建不同的实例。

下面,我展示了两种未记录的重置可编译 lambda 的方法,但我不知道它们是否会在运行时产生正确的行为。

#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);
}

是否有记录的方法可以执行此操作,如果没有,这两种解决方案是否可以安全使用?

最佳答案

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

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

便携、易于阅读且明显正确。


另外,

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

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

关于c++ - 是否有记录的方法来重置现有 std::exponential_distribution 对象上的 lambda 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43195248/

相关文章:

c++ - 球坐标映射创建双 epsilons

c++ - unique_ptr 运行时错误

c++ - C++11 是否允许在标识符中使用美元符号?

Matlab:卡方拟合(chi2gof)来测试数据是否呈指数分布

c++ - 是否存在无法锁定(提升为 shared_ptr)的 weak_ptr 之类的东西?如果不是,为什么?

c++ - 如何在 R 包之间共享基于 Rcpp 的库中的 C++ 函数?

c++ - 如何生成具有指数分布(均值)的随机数?

python - 如何在 python 中使用 MLE 来拟合双指数分布?

c++ - 是否可以从 C++ 中的线程返回退出代码?

c++ - 模板参数无效