我想打印最大值的行,它在c++中有4到5列

I want to print the largest value row which has 4 5 columns in c++

本文关键字:中有 c++ 5列 它在 打印 想打 最大值      更新时间:2023-10-16

我想打印最大值的行,它在c++中有4-5列。我有两个类,一个是cpu,另一个是进程。如何将一个值从进程发送到cpu,并在将该值更新到数组后,cpu将其发送回进程。

请给我举个简单的例子。

在两个类之间传递值

通常,一个类有一个receive方法,另一个类用一个值调用receive方法。

class CPU
{
  const unsigned int MAX_ROWS = 10U;
  const unsigned int MAX_COLS = 45U;
  int matrix[MAX_ROWS][MAX_VALUES];
public:  
  void receive(unsigned int row, unsigned int column, int value)
  {
    matrix[row][col] = value;
  }
};
class Process
{
  CPU & m_cpu_object;
public:
  Process(CPU & cpu_object)
  : m_cpu_object(cpu_object)
  { ; }
  void send_to_cpu(void)
  {
    for (unsigned int row = 0; row < 5; ++row)
    {
      for (unsigned int column = 0; column < 10; ++col)
      {
        m_cpu_object.receive(row, column, row * column);
      }
    }
  }
};
int main(void)
{
  CPU my_cpu;
  Process process_1(my_cpu);
  process.send_to_cpu();
  return 0;
}

查找具有最大值的行

该解决方案与查找一组值中的最大值非常相似。

您需要维护两个变量,一个包含运行中的最大值,另一个维护包含最大值的行索引。

处理完所有行后,打印由行索引指示的行。

示例:

unsigned int row_of_max = 0;
int max_value = -123456789;
for (unsigned int row = 0; row < MAXIMUM_ROWS; ++row)
{
  for (unsigned int col = 0; col < MAXIMUM_COLUMNS; ++col)
  {
    if (maxtrix[row][col] > max_value)
    {
      row_of_max = row;
      max_value = maxtrix[row][col];
    }
  }
}

行或列的数量,无论是4或5,都不重要;算法仍然是一样的。