fork download
  1. #include <iostream>
  2. #include <utility>
  3.  
  4. const std::size_t NROWS = 5, NCOLS = 3 ;
  5.  
  6. // return true on success, with row,col set to the indices
  7. // return false if not found, with row set to NROWS,col set to NCOLS
  8. bool find_1( const int array[NROWS][NCOLS], int value, std::size_t& row, std::size_t& col )
  9. {
  10. for( row = 0 ; row < NROWS ; ++row )
  11. for( col = 0 ; col < NCOLS ; ++col )
  12. if( array[row][col] == value ) return true ;
  13.  
  14. return false ; // not fomd, row == NROWS, col == NCOLS
  15. }
  16.  
  17. // return a pair of row, col indices on success
  18. // returen the pair NROWS,NCOLS if not found
  19. std::pair<std::size_t,std::size_t> find_2( const int array[NROWS][NCOLS], int value )
  20. {
  21. for( std::size_t row = 0 ; row < NROWS ; ++row )
  22. for( std::size_t col = 0 ; col < NCOLS ; ++col )
  23. if( array[row][col] == value ) return { row, col } ;
  24.  
  25. return { NROWS, NCOLS } ; // not fomd, return pair NROWS,NCOLS
  26. }
  27.  
  28.  
  29. // return offset from array[0][0] on success
  30. // return NROWS * NCOLS if not found
  31. std::size_t find_3( const int array[NROWS][NCOLS], int value )
  32. {
  33. const std::size_t BEYOND = NROWS * NCOLS ;
  34. for( std::size_t pos = 0 ; pos < BEYOND ; ++pos )
  35. if( array[0][pos] == value ) return pos ;
  36. return BEYOND ; // not found
  37. }
  38.  
  39. int main()
  40. {
  41. const int a[NROWS][NCOLS]
  42. {
  43. { 0, 1, 2 },
  44. { 3, 4, 5 },
  45. { 6, 7, 8 },
  46. { 9, 10, 11 },
  47. { 12, 13, 14 },
  48. };
  49.  
  50. std::size_t row, col ;
  51.  
  52. if( find_1( a, 7, row, col ) )
  53. std::cout << "found " << a[row][col] << " at " << row << ',' << col << '\n' ;
  54.  
  55. const auto p = find_2( a, 7 ) ;
  56. row = p.first ;
  57. col = p.second ;
  58. if( row < NROWS )
  59. std::cout << "found " << a[row][col] << " at " << row << ',' << col << '\n' ;
  60.  
  61. const auto offset = find_3( a, 7 ) ;
  62. if( offset < NROWS*NCOLS )
  63. std::cout << "found " << a[0][offset] << " at offset " << offset << '\n' ;
  64. }
  65.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
found 7 at 2,1
found 7 at 2,1
found 7 at offset 7