[英]Using std::transform with std::normal_distribution and std::bind
stl c++11 solution : 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()));
Easy range-based loop : 简单的基于范围的循环:
for (auto& d : data) {
d += distribution();
}
My STL solution doesn't work as it always take the first number it generated from the distribution. 我的STL解决方案无法正常工作,因为它始终采用从发行版本生成的第一个数字。 I tried with the placeholder as the 3rd parameter but it doesn't change anything. 我尝试使用占位符作为第三个参数,但它没有任何改变。 All of my data is incremented by the same number which is not something I want. 我所有的数据都增加了相同的数字,这不是我想要的。 I want the same behaviour as the range-based loop. 我想要与基于范围的循环相同的行为。
It this something possible? 这有可能吗?
Let's rewrite your second bind
as lambda, to get a feeling how it actually works: 让我们将第二个bind
重写为lambda,以了解其实际工作方式:
auto func = std::bind(std::plus<double>(), std::placeholders::_1, distribution())
is equivalent too 也一样
auto d = distribution();
auto func = [d](double x){ return std::plus<double>()(x,d); };
or, if we use C++14's initialization feature: 或者,如果我们使用C ++ 14的初始化功能:
auto func = [d=distribution()](double x){ return std::plus<double>()(x,d); };
As you can see, distribution()
gets called only once. 如您所见, distribution()
仅被调用一次。 However, you don't want to use the return value of distribution
, you want to call distribution
for every call of func
. 但是,您不想使用distribution
的返回值,而是想为func
每次调用都调用distribution
。 While it's possible to do that with bind
, a lambda will make this a lot easier: 尽管可以使用bind
来做到这一点,但是lambda会使事情变得容易得多:
std::transform(data.begin(), data.end(), data.begin(),
[&distribution](double x){ return x + distribution(); });
And in my opinion, that's a lot easier to read than your previous bind
. 我认为,这比以前的bind
更容易阅读。 Note that std::bind
(or rather boost::bind
) predates lambdas. 请注意, std::bind
(或更确切地说boost::bind
)早于lambda。 There were some issues with lambdas in C++11 compared to std::bind
, but with C++14, lambdas are usually a lot easier to handle, read and understand without sacrificing much. 与std::bind
相比,C ++ 11中的lambdas存在一些问题 ,但是对于C ++ 14,lambdas通常更容易处理,阅读和理解而又不付出太多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.