当我查看 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/