首页 > 解决方案 > 将值从一个函数传递到另一个 C++

问题描述

我正在编写两个函数:其中一个是用随机值“填充”数组,而第二个函数我必须使用相同的数组,选择一行并找到该行的最小元素。

但问题是我不知道如何将值从一个函数传递到另一个函数。

这是我的代码:

#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

void fillarray(int arr[5][5], int rows, int cols) {
    cout << "Static Array elements = \n\n" << flush;

    for(int i = 0; i < rows; ++i) {
        cout << "Row " << i << "  ";
        for(int j = 0; j < cols; ++j) {
            arr[i][j] = rand() % 10;
            cout << arr[i][j] << " " << flush;
        }
        cout << endl;
    }
    cout << " \n\n";
}

void minarray(int a, void fillarray) { // don't know what to write here

there:
    int min = INT_MAX; // Value of INT_MAX is 2147483648.

    if(a > 4) {
        cout << "Invalid input! " << endl;
        goto there;
    }

    for(int counter = 0; counter < 5; ++counter) {
        if(arr[a][counter] < min) min = arr[a][counter];
    }
    cout << "Minimum element is " << min << endl;
}
int main() {
    int z;

    srand(time(NULL));
    const int rows = 5;
    const int cols = 5;
    int arr[rows][cols];
    fillarray(arr, rows, cols);
    cout << "Enter the number of row: ";
    cin >> z;
    minarray(z, fillarray) 
    system("PAUSE");
}

标签: c++function-declaration

解决方案


对于初学者来说,这个函数fillarray有冗余参数cols,因为这个数字是从第一个参数的声明中知道的int arr[5][5]

Th函数可以声明为

void fillarray(int arr[5][5], int rows )

cols如果没有在函数中填充整个数组,您可以提供参数。

您已经通过此调用填充了数组

fillarray ( arr, rows, cols );

该函数执行了它的任务。因此,当您尝试时,无需再次引用该函数

minarray(z, fillarray)

该函数minarray可以声明为

void minarray( const int arr[], size_t n );

并称为

minarray( arr[z], cols );

初步检查 z 小于 5。

或者可以声明为

void minarray( const int arr[][5], size_t n, size_t row );

并称为

minarray( arr, rows, z );

请注意,有一种标准算法std::min_element允许在数组中找到最小元素。并且要使用值填充数组,您可以使用标准算法std::generate

每个功能应该只做一个任务。例如,函数fillarray应该默默地用值填充数组。要输出数组,您可以编写一个单独的函数。


推荐阅读