Search code examples
c++matrixminimum

C++ Find the minimum value in every row of a n*m matrix


How can I find the minimum value in every row of a n*m matrix, and put these values to a new array? I have this code so far, but it's not working properly:

void min(const int t[max_city][max_bird], int allmin[], int n, int m)
{
    int min=t[0][0];
    for(int i=0; i<n; ++i)
    {
        for(int j=0; j<m; ++j)
        {
            if(t[i][j]<min)
            {
                min=t[i][j];
            }
        }
        allmin[i]=min;
        cout << i+1 << ". min: " << allmin[i] << endl;
    }
}

Solution

  • Declare min inside the first loop, and initialize it there:

    for(int i=0; i<n; ++i)
    {
       int min= INT_MAX; //do this here so that it gets initialized each time!
    
       for(int j=0; j<m; ++j)
       {
          //your code
       }
       //etc
    }
    

    To use INT_MAX, include <climits>.


    Using std::min_element, your function can be re-written as:

    void min(const int t[max_city][max_bird], int allmin[], int n, int m)
    {
        for(int i=0; i<n; ++i)
        {
            allmin[i] = *std::min_element(t[i], t[i] + m);
        }
    }
    

    It became so short!

    The function std::min_element returns the pointer to the minimum element, so you dereference the returned pointer to get the value (of the minimum element).

    To use std::min_element in your program, you have to include this header:

    #include <algorithm>
    

    Hope that helps.