找到2D数组C ++中每行的最大值 [英] Finding the maximum value of every row in 2D array C++

查看:188
本文介绍了找到2D数组C ++中每行的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法找到我的二维数组的每一行的最小值与这

I've managed to find the minimum value of every row of my 2D array with this

void findLowest(int A[][Cm], int n, int m)
{
    int min = A[0][0];
    for (int i = 0; i < n; i++)
    {
         for (int j = 0; j < m; j++)
         {
             if (A[i][j] < min)
             {
                 min = A[i][j];
             }
         }
     out << i << " row's lowest value " << min << endl;
    }
}

我试图找到每个行使用相同的方式,但它只显示我第一个最大值

I'am trying to find the maximum value of every row using the same way,but it only shows me first maximum value

void findHighest(int A[][Cm], int n, int m)
{
     int max = A[0][0];
     for (int i = 0; i < n; i++)
     {
         for (int j = 0; j < m; j++)
         {
             if (A[i][j] > max)
             {
                max = A[i][j];
             }
         }
     out << i << " row's highest value " << max << endl;
     }
}

我找不到第二个函数有什么问题为什么它只显示我找到的第一个最大值。任何帮助?

I can't find what's wrong with the second function and why is it only showing me the first maximum value it finds. Any help ?

推荐答案

两个函数都返回整个数组而不是每一行的结果 max 一次,而不是每行一次。你可以得到每行的结果如下:

Both functions return the result (maximum or minimum) for the whole array rather than each row, because you set max once rather than once per row. You can get the result for each row as follows:

void findHighest(int A[][Cm], int n, int m)
{
     for (int i = 0; i < n; i++)
     {
         int max = A[i][0];
         for (int j = 1; j < m; j++)
         {
             if (A[i][j] > max)
             {
                max = A[i][j];
             }
         }
         // do something with max
     }
}

,或者更好地使用标准库函数 max_element

or, even better, use the standard library function max_element:

void findHighest(int A[][Cm], int n, int m)
{
     if (m <= 0) return;
     for (int i = 0; i < n; i++)
     {
         int max = *std::max_element(A[i], A[i] + m);
         // do something with max
     }
}

应该给你所有易于检查的值:

This should give you all values which is easy to check:

#include <algorithm>
#include <iostream>

enum { Cm = 2 };

void findHighest(int A[][Cm], int n, int m) {
  if (m <= 0) return;
  for (int i = 0; i < n; i++) {
    int max = *std::max_element(A[i], A[i] + m);
    std::cout << max << " ";
  }
}

int main() {
  int A[2][2] = {{1, 2}, {3, 4}};
  findHighest(A, 2, 2);
}

列印 2 4

这篇关于找到2D数组C ++中每行的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆