Why boost uniform_int_distribution takes a closed

2019-06-24 14:37发布

问题:

The title says it all. There's even a warning in the documentation pages:

Why do this, when the common practice in C++ is to use open ranges [begin, end) ?

回答1:

Only with closed ranges, you can create a uniform_int_distribution, that produces any integer:

uniform_int_distribution<int> dist(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());

If this would be a half-open range, you could never reach std::numeric_limits<int>::max(), but only std::numeric_limits<int>::max() - 1.

It's the same situation for std::uniform_int_distribution in the C++11 standard library.

Half-open ranges for iterators are common, because one can easily express empty ranges (by setting begin == end). This doesn't make sense for distributions.


Reference: Stephan T. Lavavej mentions this exact reason in his talk "rand() Considered Harmful" at Going Native 2013 (around minute 14). This talk is about C++11 <random>, but of course the same reasoning applies to boost as well.



标签: c++ boost