Running through entire range of `unsigned char` in `for` loop

前端 未结 3 618
野的像风
野的像风 2021-01-23 05:43

I would like to run through the entire range of unsigned char in a for loop. Say I want to print all numbers from 0 to 255, how should I go about accom

相关标签:
3条回答
  • 2021-01-23 06:22

    Try,

    unsigned char i = 0 ;
    do {
      cout << i << endl ;
    }
    while ( ++i ) ;
    

    The benefit of do .. while over the other forms is you get one free run before the condition is tested. This is an important tool for that reason (if only infrequently used), in a programmer's toolbox.

    0 讨论(0)
  • 2021-01-23 06:26

    Using boost::irange could be considered elegant (live example):

    #include <boost/range/irange.hpp>
    #include <iostream>
    
    int main()
    {
        for(auto i : boost::irange(0, 256) )
            std::cout << i << "\n";
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-23 06:27

    You can break it up:

    for (unsigned char i = 0; i < 16; ++i)
    {
        unsigned char base=i*16;
        for (unsigned char j = 0; j < 16; ++j)
        {
            unsigned char val=base+j;
            std::cout << val << std::endl;
        }
    }
    
    0 讨论(0)
提交回复
热议问题