C++ 在 2D std::vector 中查找最大值的位置
c++ find position of maximum value in 2D std::vector
假设我们有 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;
}
相关文章:
- 在二维向量的每一列中查找最大值
- 用于在具有更新查询的二维矩阵中查找最大值的最佳数据结构
- 性能:在 ARR(允许平局)中查找最大值的索引
- 使用动态内存分配和指针查找最大值、最小值和平均值
- C++ 在 2D std::vector 中查找最大值的位置
- 在对象向量中查找最大值
- 查找最大值并删除 2D 数组中的该行.C++
- C++查找最大值和最小值的功能
- 在字符串中查找最大值
- 使用数组查找最大值
- C++函数在一个双精度数组中查找最大值
- 如何查找最大值和最小值
- C++:在数组中查找最大值的问题
- Std::数组查找最大值函数
- 在数组中查找最大值,从索引的两侧增加值
- 数组函数查找最大值
- 正在数组中查找最大值
- 在二维数组的矩形区域内查找最大值的快速方法
- 浮点比较C++-查找最大值
- 查找最大值和最小值