Searching a value in an 2 dimensional array (matrix).
2 Likes
int main()
{
const size_t N = 3;
int a[N][N] =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int value = 9;
auto it = std::find( reinterpret_cast<int *>( a ),
reinterpret_cast<int *>( a ) + N * N,
value );
if ( it != reinterpret_cast<int *>( a ) + N * N )
{
size_t n = std::distance( reinterpret_cast<int *>( a ),
it );
std::cout << "Row = " << n / N << ", Column = " << n % N << std::endl;
}
size_t row = 0;
size_t col = 0;
for ( ; row < N; row++ )
{
col = 0;
while ( col < N && a[row][col] != value ) col++;
if ( col != N ) break;
}
if ( row != N )
{
std::cout << "Row = " << row << ", Column = " << col << std::endl;
}
return 0;
}
1 Like