2 ms·
That is a good point. The motivation for casting the size to int, rather than the other way around, is to get it out of "unsigned world" (where people often rea
by cannam 12y ago
That is a good point. The motivation for casting the size to int, rather than the other way around, is to get it out of "unsigned world" (where people often reason badly about even simple arithmetic) and into "signed world" as simply as possible. Often where this is going on, the container is expected to be small, but of course that's a hazardous intuition as well.
Maybe I need a little helper:
template<typename T, typename C>
bool is_in_range(T i, const C &container)
{
if (i < 0) return false;
if (sizeof(T) > sizeof(typename C::size_type)) {
return i < static_cast<T>(container.size());
} else {
return static_cast<typename C::size_type>(i) < container.size();
}
}
then
if (is_in_range(i, container)) ...