C++ find position of maximum value in 2D std::vector

cmaxstdvectorvector

Suppose we have 2D vector of int like:

1   4   3   0
1   5   6   3
2   0   0   1
6   5   9*  3
3   5   4   2

Now How can I find the position of maximum value in the 2D vector: [2][3]==9 in the example above.The answer would be 2,3

I know I can use std::max_element() but it gives iterator.

Another point is that I don't want find maximum value first and then find its location using std::find() method.(Because it's not efficient)

Indeed how can I define custom compare function to do this task with single iteration.

Many thanks.

Best Answer

int Array[4][4] = { {2, 3, 4, 6}, {1, 98, 8, 22}, {12, 65, 1, 3}, {1, 7, 2, 12}};

struct location
    {
       int x;
       int y;
    };

int main()
{
    int temp = 0;
    location l;

    for(int i = 0; i < 4; i++)
        for(int j = 0; j< 4; j++)
            if(temp < Array[i][j])
            {
                temp = Array[i][j];
                l.x = i+ 1;
                l.y = j+ 1;
            }

            cout<<"Maximum Value is "<<temp<<" And is found at ("<<l.x<<","<<l.y<<")";
system("pause");
}