Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over ALL the values

Tags:

c++

This might be an odd question, but how does one nicely loop over ALL values of a type. In particular the standard integral types such as unsigned short. A normal for loop construct presents a difficulty: what condition to use to exit the loop - because all values are valid.

Of course, there are several ways to get the job done. Exit on the last value then handle that after the loop. Use a bigger int to count. The question is, is there a more elegant way?

like image 999
wxffles Avatar asked Nov 21 '25 10:11

wxffles


2 Answers

If you want a pretty solution you can do this:

for(auto x : everyvalue<short>()) {
  std::cout << x << '\n';
}

Where everyvalue is:

#include <limits>
template<typename T>
struct everyvalue {
  struct iter {
    T x;
    bool flag;
    inline iter operator++() {
      if(x == std::numeric_limits<T>::max())
        flag = true;
      else
        ++x;
      return *this;
    }
    inline T operator*() { return x;}
    inline bool operator!=(iter& i) {return flag != i.flag;}
    // note: missing some iterator requirements, still should work
  };
  inline iter begin() { return iter{std::numeric_limits<T>::min(),0}; }
  inline iter end() { return iter{std::numeric_limits<T>::max(),1}; }
};

Otherwise a simple break would be preferred.

like image 159
Pubby Avatar answered Nov 24 '25 01:11

Pubby


I worried about this very same issue once, and this is the best I could think of:

unsigned char c = 0;
do
{
    printf("%d ", (int)c); //or whatever
} while (++c != 0);

One of the very few cases where I find the do..while syntax useful.

Note that technically it is only valid for unsigned types, as I am relying on the wrapping of values.

like image 33
rodrigo Avatar answered Nov 24 '25 02:11

rodrigo