samedi 26 mars 2016

C++: Prettiest way to iterate all values of an unsigned integer

I want to iterate all possible values of an integer. This code does not work as the termination condition never becomes false:

for (uint32_t i = 0; i <= 0xFFFFFFFF; i++)
    std::cout << i << std::endl;

I've come up with this:

auto loopBody = [](uint32_t value)
{
    std::cout << value << std::endl;
}

uint32_t last = 0xFFFFFFFF;
for (uint32_t i = 0; i < last; i++)
    loopBody(i);

loopBody(last);

It is fairly ugly, though. Is there a prettier way to do this?

Aucun commentaire:

Enregistrer un commentaire