我想在二维数组C ++中找到每一行的最大值

时间:2015-12-22 21:43:08

标签: c++ arrays 2d max row

我已经编写了这段代码,但如果我在数组中输入负值,它就无法正常工作。我该怎么办?!!

#include <iostream>
using namespace std;

void maxRow(int arr[][2],int row) {
    for (int i = 0; i < row; i++) {
        int valueMax = arr[i][0];
        for (int j = 0; j < 2; j++) {
            if (arr[i][j] > valueMax) {
                valueMax = arr[i][j];
                cout << valueMax << endl;
            }
        }
    }
}

int main() {
    int numbers[6][2] = {1,10,5,6,7,8,19,89,-2,17,-3,-7};
    maxRow(numbers, 6);
}

3 个答案:

答案 0 :(得分:0)

你的cout应该在内部for循环之外。在您的示例中,每行中的第二个元素是较大的元素,因此代码似乎可以工作。

答案 1 :(得分:0)

这是对的吗?

#include <iostream>
using namespace std;

void maxRow(int arr[][2],int row) {
    for (int i = 0; i < row; i++) {
        int valueMax = arr[i][0];
        for (int j = 0; j < 2; j++) {
            if (arr[i][j] > valueMax) {
                valueMax = arr[i][j];
            }
        }
        cout << valueMax << endl;
    }
}

int main() {
    int numbers[3][2] = {{1,2}, {19, 2}, {-2, -5}};
    maxRow(numbers, 3);
}

答案 2 :(得分:0)

您可以在循环中使用std::max_element,其中每次迭代都会存储当前最大值或std::max_element的返回值中的较大者。

#include <iostream>
#include <climits>
#include <algorithm>

void maxRow(int arr[][2],int row) 
{
    int curMax = INT_MIN;
    for (int i = 0; i < row; i++) 
    {
        curMax = std::max(curMax, 
                          *std::max_element(&arr[i][0], &arr[i][2]));
    }
    std::cout << curMax;
}

int main() {
    int numbers[6][2] = {1,10,5,6,7,8,19,89,-2,17,-3,-7};
    maxRow(numbers, 6);
}

Live Example