![](/img/trans.png)
[英]binding std::normal_distribution to a std::function for storage in std::vector
[英]Using std::transform with std::normal_distribution and std::bind
stl c ++ 11解决方案:
auto distribution = std::bind(std::normal_distribution<double>{mean, stddev},
std::mt19937(std::random_device{}())
);
std::transform(data.begin(), data.end(), data.begin(),
std::bind(std::plus<double>(), std::placeholders::_1, distribution()));
简单的基于范围的循环:
for (auto& d : data) {
d += distribution();
}
我的STL解决方案无法正常工作,因为它始终采用从发行版本生成的第一个数字。 我尝试使用占位符作为第三个参数,但它没有任何改变。 我所有的数据都增加了相同的数字,这不是我想要的。 我想要与基于范围的循环相同的行为。
这有可能吗?
让我们将第二个bind
重写为lambda,以了解其实际工作方式:
auto func = std::bind(std::plus<double>(), std::placeholders::_1, distribution())
也一样
auto d = distribution();
auto func = [d](double x){ return std::plus<double>()(x,d); };
或者,如果我们使用C ++ 14的初始化功能:
auto func = [d=distribution()](double x){ return std::plus<double>()(x,d); };
如您所见, distribution()
仅被调用一次。 但是,您不想使用distribution
的返回值,而是想为func
每次调用都调用distribution
。 尽管可以使用bind
来做到这一点,但是lambda会使事情变得容易得多:
std::transform(data.begin(), data.end(), data.begin(),
[&distribution](double x){ return x + distribution(); });
我认为,这比以前的bind
更容易阅读。 请注意, std::bind
(或更确切地说boost::bind
)早于lambda。 与std::bind
相比,C ++ 11中的lambdas存在一些问题 ,但是对于C ++ 14,lambdas通常更容易处理,阅读和理解而又不付出太多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.