求一个N行M列的二维数组中元素的最大值和最小值
答案:3 悬赏:0
解决时间 2021-02-12 16:46
- 提问者网友:追忆成伤
- 2021-02-11 18:51
求一个N行M列的二维数组中元素的最大值和最小值
最佳答案
- 二级知识专家网友:怪咖小青年
- 2021-02-11 19:18
不管是几维数组,都可以用stl中的min_element()和max_element()来取最大值和最小值。请看下面的例子:
#include<iostream>
#include<algorithm>
using namespace std;
void main()
{
const int N = 2;
const int M = 3;
int a[N][M] = { {1,2,3}, {4,5,6} };
int *min_ptr = min_element( &a[0][0], &a[N-1][M] );
int *max_ptr = max_element( &a[0][0], &a[N-1][M] );
cout << *min_ptr << " " << *max_ptr;
}
#include<iostream>
#include<algorithm>
using namespace std;
void main()
{
const int N = 2;
const int M = 3;
int a[N][M] = { {1,2,3}, {4,5,6} };
int *min_ptr = min_element( &a[0][0], &a[N-1][M] );
int *max_ptr = max_element( &a[0][0], &a[N-1][M] );
cout << *min_ptr << " " << *max_ptr;
}
全部回答
- 1楼网友:摧毁过往
- 2021-02-11 21:41
可以设置一个滑动指针,先是行滑动,再是列滑动,再设置一个变量,随着指针的滑动,用变量的值与二维数组的值进行比对,将大的值换如变量中,同时记录下该数值的行数和列数,循环一周后变量得到的值即为最大值!
- 2楼网友:陪衬角色
- 2021-02-11 20:27
只写操作部分,其他部分自己补全吧
int max, min, i, j;
for (i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
{
if (i == 0 && j == 0)
{
max = min = a[i][j];
}
else
{
if (max < a[i][j])
{
max = a[i][j];
}
if (min > a[i][j])
{
min = a[i][j];
}
}
}
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯