Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over the full range of an integer type

Tags:

c++

iteration

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.

like image 625
Chris_F Avatar asked Oct 29 '25 18:10

Chris_F


2 Answers

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++;
}
like image 149
Brian Bi Avatar answered Oct 31 '25 09:10

Brian Bi


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.

like image 43
thus spake a.k. Avatar answered Oct 31 '25 07:10

thus spake a.k.