使用std ::用std :: normal_distribution和std :: bind
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
)早于Lambdas。与std::bind
相比,C 11中的Lambdas有一些问题,但是C 14,Lambdas通常更容易处理,阅读和理解而不牺牲太多。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 可组合的lambda/std::函数与std::可选