如何在二维数组 ROW 中找到最小值和最大值?

How to find a minimum and maximum value in a 2D array ROW?

我有一个程序生成 10 5 并且用户输入数据。我的问题是,如何找到每一行中的最大值和最小值?我已经为此工作了一个小时,但无法弄清楚。我曾多次尝试解决这个问题;这是我当前的代码。

#include <iostream>
#include <iomanip>
using namespace std;

int returnMax(int[][]);
int main() 
{
    double sales[10][5];
    string name[10];
    double highest;
    double lowest;
    double avg;
    // Populating table
    for (int row = 0; row < 1; row++) 
    {
        cout << "Enter the salesman's name: " << endl;
        cin >> name[row];
        cout << "Enter the amount of sales for the five years" << endl;
        for (int col = 0; col < 5; col++) {
            cin >> sales[row][col];
        }
    }
    cout << returnMax(sales[1][0]) << endl;
    return 0;
}

int returnMax(int a[][]) 
{
    int max;
    for (int i = 0; i < 1; i++) {
        max = a[i][0];
        for (int j = 0; j < 5; j++) {
            if (a[i][j] > max)
                max = a[i][j];
        }
    }
    return max;
}

首先,这样准备你的环境:

#define NROWS 10 //use a constant for number of rows
#define NCOLUMNS 5 // use a constant for number of columns

typedef int Matrix[NROWS][NCOLUMNS]; // declare the type Matrix which is 2d Array using NROWS and NCOLUMNS as size

int returnMaxForRow(int,Matrix); //If you want to know the max value of a row, you need to pass the row

所以大体上你可以这样做:

int main () {
 Matrix sales; //You don't need to specify the size, which is done before
 string name[10];
 double highest;
 double lowest;
 double avg;

 ecc....

现在你的函数应该这样做:

  int returnMaxForRow (int row, Matrix a) {
    int max = a[row][0];

    for (int i = 0; i < NCOLUMNS; i++) {
       if (a[row][i] > max){
         max = a[row][i];
       }
    }
    return max;
   }

所以你可以这样称呼它:

 cout<< returnMaxForRow(0,sales);
 cout<< returnMaxForRow(1,sales);
 cout<< returnMaxForRow(2,sales);
 cout<< returnMaxForRow(3,sales);

一些建议:

Use constants or variable to set array's index, such as define statement When you do sales[1][0] you get a single value (row 1, column 0) and not all the row Use typedef to declare custom array with different dimensions, it is easier to handle them this way

如果需要,可以将函数更改为 return 所有行的最大值。 如果你想得到矩阵的最大值,方法类似。

你的逻辑:

cout << returnMax(sales[1][0]) << endl;

错了。 sales[1][0] 整个 sales 数组 的唯一一个元素。这意味着, sales[1][0] = element of 1st row and 0th columnsales 数组中,您 没有初始化任何值 。因为您在整个数组中 只初始化了一行 ,因为您有以下行:

for (int row = 0; row < 1; row++)

记住在 C++ 中索引从 0 开始,而不是从 1 开始。话虽这么说,上面的结果(未初始化的变量)将导致你有undefined behavior.


建议:

  1. 在现代 C++ 中,您有比使用原始数组更好的选择。为了 例如,使用 std::vector<>std::array<> 使您的代码既简单又安全。在你的情况下,你可以 有

    std::vector<int> sales(50, 0) // one dimentional: with 10 * 5 entries
    

    并相应地操作行参见解决方案-1

    std::vector<std::vector<int>> sales(10, std::vector<int>(5, 0));
                          // two dimensional: with 10 rows and 5 columns
    

    并使用 range-based for 循环,这样你就永远不会得到 越界问题(见解2).

  2. 关于查找每行条目的最小值和最大值,您可以 简单地应用算法函数调用 std::minmax_element 来自 algorithm header.


示例解决方案 - 1

使用one-dimensional向量数组的示例解决方案如下所示:SEE LIVE

#include <iostream>
#include <vector>    // std::vector
#include <algorithm> // std::minmax_element
#include <string>

int main()
{
    constexpr std::size_t rawMax = 2;
    constexpr std::size_t colMax = 5;
    // one dimentional array with size = (rawMax * colMax)
    std::vector<int> sales(rawMax * colMax, 0);
    std::vector<std::string> name(rawMax);

    // Populating table
    for (std::size_t row = 0; row < rawMax; ++row)
    {
        std::cout << "Enter the salesman's name: "; std::cin >> name[row];
        std::cout << "Enter the amount of sales for the five years: " ;
        for (std::size_t col = 0; col < colMax; ++col)
            std::cin >> sales[(row*colMax) + col]; // convert col and raw to 1D index.
    }
    /// get the begin and end of each row as iterators
    auto rowBeginIter = sales.begin();
    auto rowEndIter = sales.begin() + colMax - 1;
    for (const std::string& str: name)
    {
        std::cout << "salesman's name: "; std::cout << str;
        auto getMinMaxRow = std::minmax_element(rowBeginIter, rowEndIter + 1);
        std::cout << " min: " << *getMinMaxRow.first
                  << " max: " << *getMinMaxRow .second << std::endl;
        rowBeginIter += colMax;  // increment both iterator to the next raw
        rowEndIter += colMax;
    }
    return 0;
}

示例解决方案 - 2

使用向量的向量(2D)的示例解决方案如下所示:SEE LIVE

#include <iostream>
#include <vector>    // std::vector
#include <algorithm> // std::minmax_element
#include <string>

int main()
{
    constexpr std::size_t rawMax = 2; // to test
    constexpr std::size_t colMax = 5;
    // initilize thw 2D vector of vectors with (rawMax x colMax)
    std::vector<std::vector<int>> sales(rawMax, std::vector<int>(colMax, 0));
    // initilize with  0's with a size that of maximum number of rows.
    std::vector<std::string> name(rawMax, "");
    // Populating table
    for (std::size_t row = 0; row < rawMax; row++)
    {
        std::cout << "Enter the salesman's name: "; std::cin >> name[row];
        std::cout << "Enter the amount of sales for the five years: " ;
        for (std::size_t col = 0; col < colMax; col++) {
            std::cin >> sales[row][col];
        }
    }
    /* print max and min of each person
     * use range based for loops to loop through them
     * (optional: index based loops can also be used like above)
     */
    auto nameIter = name.cbegin();
    for(const std::vector<int>& each_row: sales)
    {
        std::cout << "salesman's name: "; std::cout << *nameIter << "\t";
        auto getMinMaxRow = std::minmax_element(each_row.cbegin(), each_row.cend());
        std::cout << " min: " << *getMinMaxRow.first
                  << " max: " << *getMinMaxRow.second << std::endl;
        ++nameIter; // increment the iterator of name-vector
    }
    return 0;
}