If a class provides begin and end functions returning iterator objects, and that iterator has a != operator, then the class can be used in a range based for. Here’s an example that allows for iterating over all the bits in an integer. For example, suppose that
0b10101010
is a representation of the set:
128, 32, 8, 2
or
1<<7, 1<<5, 1<<3, 1<<1
We can iterate over the set with a set of bit shifts, and use the following setup to do so
class bititer
{
unsigned bset ;
int cur{} ;
public:
bititer( const unsigned b )
: bset{ b }
{
}
bititer & operator++()
{
bset >>= 1 ;
cur++ ;
return *this ;
}
unsigned operator*()
{
unsigned v{} ;
if ( bset & 1 )
{
v = ( 1 << cur ) ;
}
return v ;
}
bool operator !=( const bititer & b )
{
return ( bset != b.bset ) ;
}
} ;
Iteration can now be done once a container adapter that provides the begin and end functions is implemented:
struct bitset
{
unsigned bits ;
bititer begin()
{
return bititer{ bits } ;
}
bititer end()
{
return bititer{ 0 } ;
}
} ;
int main()
{
for ( auto v : bitset{ 0b10101010 } )
{
std::cout << v << "\n" ;
}
return 0 ;
}
Note that the 0b10101010 syntax is from c++14, not c++11.