我使用的是Visual 2013 (调试模式),它没有基于迭代器的std::discrete_distribution构造函数,所以我使用的是解决方案。但是,在使用此解决方案时,如果最后一个元素不大于weights中的第一个元素,则会产生运行时错误。
使用初始化列表时不会产生此错误。
示例:
#include <iostream>
#include <random>
#include <vector>
int main(){
std::discrete_distribution<> dist1 = { 10.f,11.f,5.f };
std::cout << "!" << std::endl;
std::vector<float> weights = { 10.f, 11.f, 5.f};
std::size_t i(0);
std::discrete_distribution<> dist2(weights.size(), weights.front(), weights.back(),
[&weights, &i](double){
auto w = weights[i];
++i;
return w;
});
std::cout << "!!" << std::endl;
return 0;
}输出: 好了! discrete_distribution的无效范围
将大于10的任何数字添加到weights的末尾将停止运行时错误的发生。
为什么会发生这种情况?
发布于 2014-02-23 19:47:44
您正在使用描述为这里的第三个构造函数,即:
template< class UnaryOperation >
discrete_distribution( std::size_t count, double xmin, double xmax,
UnaryOperation unary_op );std::discrete_distribution实例的正确初始化要求
delta * 2 = (xmax - xmin) > 0。
发布于 2014-06-12 04:14:59
为了解决这个问题,您的lambda实际上并没有使用xmin和xmax (或者fw的结果)来计算权重,所以不要担心重新排序数组。只要传递0和1(或xmin
std::discrete_distribution<> dist2(weights.size(), 0, 1,
[&weights, &i](float){
auto w = weights[i];
++i;
return w;
});
示例:http://ideone.com/351Jhg
https://stackoverflow.com/questions/21973069
复制相似问题