how to use "max_element"

hello everybody,

can anyone tell me how to use "max_element" of the STL algorithm for finding the maximum in each line of a matrix (2D array) of doubles?

thank you
max_element(my_matrix+i*N, my_matrix+(i+1)*N); should return the max element of i'th row. This won't work for columns.
std::max_element returns an iterator that points to the maximum element.

The general invoking of it looks like

std::max_element( std::begin( conteiner ), std::end( container ) );

where container is any arbitrary standard container or an array.

Let assume that you have a two-dimensional array and you need to print the maximum element in every row of the array. You can use in this case two standard algorithms together.

1
2
3
4
5
6
int a[M][N];
...
std::for_each ( std::begin( a ), std::end( a ),
                       [] ( const int ( &x )[N] )
                       { std::cout << *std::max_element( std::begin( x ), std::end( x ) )
                                       << std::endl; } );


I did not test the code but I hope it will work.
Last edited on
Thanks ;)
Topic archived. No new replies allowed.