Chris_F
Chris_F

Reputation: 5567

Iterating over the full range of an integer type

My first question is, what is the best way to iterate over the entire range of possible values for a particular type? There seems to be no really clean way to accomplish this.

Upvotes: 4

Views: 849

Answers (3)

Mooing Duck
Mooing Duck

Reputation: 66991

Iterating over a small type can be done by first converting to a larger type that has a larger size. Easy. (Note, long long is almost always larger than int, but is not guaranteed to be.)

for(long long i = INT_MIN; i<=INT_MAX; ++i) 
    ^^^^^^^^^

Alternatively, seperate the last one out:

for(int i=INT_MIN; i<INT_MAX; ++i)
    do_thing(i);
do_thing(INT_MAX); //get the last one 

If you want to iterate over a large type (long long or unsigned long long), I'd have to wonder what you're doing, because that would take something on the order of four hundred years to simply iterate, much less do anything with them (assuming a 3.0GHz single core processor). Iterating over the 64bit range with the worlds fastest supercomputer Tianhe-2 would take ~12 days.

Upvotes: 2

thus spake a.k.
thus spake a.k.

Reputation: 1637

For an integer type T you can use

const T i0 = std::numeric_limits<T>::min();
const T in = std::numeric_limits<T>::max();

for(T i=i0;i!=in;++i) do_something(i);
do_something(in);

Floating point types are a bit trickier. IEEE754 defines an operation that allows you to step to the next representable number above (or below) any given value, but as far as I'm aware there isn't a standard C++ function that exposes it.

Upvotes: 3

Brian Bi
Brian Bi

Reputation: 119641

For an unsigned integral type,

unsigned x = 0;
do {
    // something with x
} while (++x > 0);

You can do this because unsigned integral types obey the laws of arithmetic modulo 2^n.

For a signed integral type, something like this would work, though it's a bit less clean:

int x = std::numeric_limits<int>::min();
while (true) {
    // do something with x
    if (x == std::numeric_limits<int>::max()) break;
    x++;
}

Upvotes: 3

Related Questions