C++ 在 2D std::vector 中查找最大值的位置

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

本文关键字:查找 最大值 位置 vector 2D std C++      更新时间:2023-10-16

假设我们有 int 的 2D 向量,如下所示:

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

现在我如何在上面的示例中找到 2D 向量中的最大值位置:[2][3]==9。答案是 2,3

我知道我可以使用std::max_element(),但它提供了迭代器。

另一点是我不想先找到最大值,然后使用 std::find() 方法找到它的位置。(因为它效率不高)

实际上,我如何定义自定义比较函数以通过单次迭代完成此任务。

非常感谢。

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");
}

假设它是N*N向量(在本例中为4*4),并且该向量的名称为sum

7 4 2 0 
4 8 10 8 
3 6 7 6 
3 9 19* 14

定义一维向量,如下所示

vector<int> oneDimVector;
for(int i = 0; i < 4; i++){
    for(int j = 0; j < 4; j++){
        oneDimVector.push_back(sum[i][j]);
    }
}

然后在该一维向量中找出最大元素,如下所示

vector<int>::iterator maxElement;
maxElement = max_element(oneDimVector.begin(), oneDimVector.end());

然后在矩阵中找出确切的位置,如下所示

int dist = distance(oneDimVector.begin(), maxElement);
int col = dist % 4;
int row = dist / 4;

现在您可以按预期获得位置

cout << "Max element is " << *maxElement << " at" << " " << row << "," << col << endl;

注意 - 我们假设 (0,0) 作为初始位置

它给出了元素的位置及其在

O(n)

时间,很少有 for 循环。

找到下面的代码:

#include <bits/stdc++.h>
using namespace std;
int main() {
    vector<vector<int>> a = { {2, 3, 4, 6}, {1, 98, 8, 22}, {12, 65, 1, 3}, {1, 7, 2, 12}};
    vector<int> tmp;
    //create 1-dimensional array to find the max element
    for(int i=0;i<a.size();i++){
        tmp.insert(tmp.end(),a[i].begin(),a[i].end());
    }
    //get the row and column location of the elment
    int row = (max_element(tmp.begin(),tmp.end()) -tmp.begin())/a.size();
    int col = (max_element(tmp.begin(),tmp.end()) -tmp.begin())%a.size();
    // gets the value of the max element in O(n) time
    int val = *max_element(tmp.begin(),tmp.end());
    cout<<"Max element is located at:"<<(row+1)<<","<<(col+1)<<"and the value is "<<val<<endl;
    return 0;
}