【发布时间】:2013-01-01 12:40:46
【问题描述】:
我正在尝试使用 VS2010 中的模板根据类型创建随机数。我正在使用下面的代码:
template<class BaseT>
struct distribution
{ // general case, assuming T is of integral type
typedef std::tr1::uniform_int<BaseT> dist_type;
};
template<>
struct distribution<float>
{ // float case
typedef std::tr1::uniform_real<float> dist_type;
};
template<>
struct distribution<double>
{ // double case
typedef std::tr1::uniform_real_distribution<double> dist_type;
};
template<class BaseT>
class BaseTypeRandomizer
{
public:
BaseTypeRandomizer() : mEngine(std::time(0))
{
}
void CreateValues(std::vector<BaseT>& Values, size_t nValues)
{
typedef typename distribution<BaseT>::dist_type distro_type;
std::random_device Engine;
distro_type dist(std::numeric_limits<BaseT>::min(), std::numeric_limits<BaseT>::max());
for (size_t iVal = 0; iVal < nValues; ++iVal)
{
Values[iVal] = dist(Engine);
}
}
};
不幸的是,为char/int/long 等(整数类型)创建 BaseTypeRandomizer 对象会返回覆盖整个范围的数字,但对于浮点数和双精度数则不会。花车都在1e+37 到9e+38 之间,双打是1e+307 到2e+308(或者至少都在那个附近)。在 VS 调试器中检查 dist 对象显示限制是正确的,但 Values 向量填充的数字范围要小得多。
有人知道为什么限制不能正常工作吗?
【问题讨论】:
标签: c++ visual-studio-2010 templates random numeric-limits