【问题标题】:I want to find the maximum value of each row in a 2d array C++我想在二维数组 C++ 中找到每一行的最大值
【发布时间】:2015-12-22 21:43:07
【问题描述】:

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

#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);
}

【问题讨论】:

  • 看起来像是调试器的工作。
  • 提供你期望的输出和你得到的输出。

标签: c++ arrays 2d max row


【解决方案1】:

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

【讨论】:

  • -2 和 -5 怎么样。在这一行中,第一个元素很大
【解决方案2】:

是这样吗??

#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);
}

【讨论】:

  • 你的内循环可以从j = 1而不是j = 0开始,因为valueMax是使用第i行的j = 0值初始化的。
  • 你也应该看看std::max_element
【解决方案3】:

您可以在循环中使用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

【讨论】:

    猜你喜欢
    • 2016-03-16
    • 2018-09-25
    • 2016-03-19
    • 2016-08-24
    • 2021-02-18
    • 2022-11-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    相关资源
    最近更新 更多