Well, @bitmask's answer has already said most of what I thought of saying when I read the question.
But for completeness, here's another technique:
Matrix m;
Index2D< 9, 9 > pos;
for( ; pos < pos.end(); ++pos )
{
if( m( pos.x(), pos.y() ) == 0 )
{
break;
}
}
cout << pos.x() << " " << pos.y() << endl;
IMHO this is far more clear code.
Also, the matrix can then be made to support indexing via Index2D values, thus reducing the above to just …
Matrix m;
Index2D< 9, 9 > pos;
for( ; pos < pos.end(); ++pos )
{
if( m[pos] == 0 )
{
break;
}
}
cout << pos.x() << " " << pos.y() << endl;
Since there’s nothing like Index2D in the standard library, it needs to be defined somewhere, e.g. like
template< int width, int height >
struct Index2D
{
int i_;
int x() const { return i_ % width; }
int y() const { return i_ / width; }
void operator++() { ++i_; }
bool operator<( Index2D const& other ) const
{
return (i_ < other.i_);
}
Index2D(): i_( 0 ) {}
Index2D( int const x, int const y )
: i_( width*y + x )
{}
static const Index2D endValue;
static Index2D end() { return endValue; }
};
template< int width, int height >
Index2D< width, height > const Index2D< width, height >::endValue( 0, height );
But then it can be reused everywhere that you need this functionality.