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
|
#include <iostream>
#include <algorithm>
#include <tuple>
// return the position - pair (row,col) - containing the max element
template < typename T, std::size_t NROWS, std::size_t NCOLS >
std::pair< std::size_t, std::size_t > pos_max_element( T (&matrix)[NROWS][NCOLS] )
{
const auto ptr = std::max_element( std::begin( matrix[0] ), std::end( matrix[NROWS-1] ) ) ;
const auto pos = ptr - std::begin( matrix[0] ) ;
return { pos/NCOLS, pos%NCOLS } ;
}
int main()
{
const int a[5][6] =
{
{ 12, 34, 78, 92, 51, 40 },
{ 12, 34, 78, 92, 51, 40 },
{ 12, 34, 78, 92, 51, 40 },
{ 93, 34, 78, 92, 99, 40 },
{ 12, 34, 78, 92, 95, 40 }
};
std::size_t row, col ;
std::tie(row,col) = pos_max_element(a) ; // unpack the pair into row,col
std::cout << "max element is a[" << row << "][" << col << "] == " << a[row][col] << '\n' ;
}
|