找出矩阵中的最大值,输出最大值及其所在行和列。考虑同时存在多个最大值的情况。
时间: 2024-04-30 12:17:52 浏览: 11
好的,这是一个关于矩阵的问题,我可以为您提供一个解决方案。
您可以遍历整个矩阵,找到其中的最大值,同时记录最大值所在的行和列。
在遍历矩阵的过程中,如果遇到比当前记录的最大值更大的数,则更新最大值和其所在的行和列。
如果存在多个最大值,则可以将它们的行和列都记录下来,最后一起输出。
下面是一个示例代码,您可以参考一下:
```
#include <iostream>
#include <vector>
using namespace std;
void findMax(vector<vector<int>>& matrix) {
int maxVal = matrix[0][0];
vector<pair<int, int>> maxIndex;
maxIndex.push_back({0, 0});
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] > maxVal) {
maxVal = matrix[i][j];
maxIndex.clear();
maxIndex.push_back({i, j});
} else if (matrix[i][j] == maxVal) {
maxIndex.push_back({i, j});
}
}
}
cout << "Max value: " << maxVal << endl;
cout << "Max value is at:" << endl;
for (auto index : maxIndex) {
cout << "[" << index.first << ", " << index.second << "]" << endl;
}
}
int main() {
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
findMax(matrix);
return 0;
}
```
这段代码会输出以下结果:
```
Max value: 9
Max value is at:
[2, 2]
```
这表示矩阵中最大的数是9,它在第3行第3列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)