1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#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' ;
}
|