#include <iostream>
#include <utility>
const std::size_t NROWS = 5, NCOLS = 3 ;
// return true on success, with row,col set to the indices
// return false if not found, with row set to NROWS,col set to NCOLS
bool find_1( const int array[NROWS][NCOLS], int value, std::size_t& row, std::size_t& col )
{
for( row = 0 ; row < NROWS ; ++row )
for( col = 0 ; col < NCOLS ; ++col )
if( array[row][col] == value ) return true ;
return false ; // not fomd, row == NROWS, col == NCOLS
}
// return a pair of row, col indices on success
// returen the pair NROWS,NCOLS if not found
std::pair<std::size_t,std::size_t> find_2( const int array[NROWS][NCOLS], int value )
{
for( std::size_t row = 0 ; row < NROWS ; ++row )
for( std::size_t col = 0 ; col < NCOLS ; ++col )
if( array[row][col] == value ) return { row, col } ;
return { NROWS, NCOLS } ; // not fomd, return pair NROWS,NCOLS
}
// return offset from array[0][0] on success
// return NROWS * NCOLS if not found
std::size_t find_3( const int array[NROWS][NCOLS], int value )
{
const std::size_t BEYOND = NROWS * NCOLS ;
for( std::size_t pos = 0 ; pos < BEYOND ; ++pos )
if( array[0][pos] == value ) return pos ;
return BEYOND ; // not found
}
int main()
{
const int a[NROWS][NCOLS]
{
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 },
{ 9, 10, 11 },
{ 12, 13, 14 },
};
std::size_t row, col ;
if( find_1( a, 7, row, col ) )
std::cout << "found " << a[row][col] << " at " << row << ',' << col << '\n' ;
const auto p = find_2( a, 7 ) ;
row = p.first ;
col = p.second ;
if( row < NROWS )
std::cout << "found " << a[row][col] << " at " << row << ',' << col << '\n' ;
const auto offset = find_3( a, 7 ) ;
if( offset < NROWS*NCOLS )
std::cout << "found " << a[0][offset] << " at offset " << offset << '\n' ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dXRpbGl0eT4KCmNvbnN0IHN0ZDo6c2l6ZV90IE5ST1dTID0gNSwgTkNPTFMgPSAzIDsKCi8vIHJldHVybiB0cnVlIG9uIHN1Y2Nlc3MsIHdpdGggcm93LGNvbCBzZXQg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