c++ - 将值从一个函数传递到另一个 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");
}
解决方案
对于初学者来说,这个函数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
应该默默地用值填充数组。要输出数组,您可以编写一个单独的函数。
推荐阅读
- c++ - 使用循环不使用乘法运算符将实数(分数)相乘的程序
- jhipster - 具有遗留 REST 服务的 JHipster 网关
- ubuntu - Ansible playbook 安装失败
- r - 将相同的字符串状态应用于具有相似应用程序 ID 和用户 ID 的所有行
- php - 在 WooCommerce 中向“缺货”产品变体添加联系表
- android - Retrofit 从基本 url 中删除查询参数
- python - BeautifulSoup - 使用特定字符串直接在标题下方和上方查找元素
- java - 如何更改 Android Studio for LibGDX 的起始页
- mongodb - 通过迁移到 NoSQL 来提高速度
- python - 在 Python 中递归生成每个井字游戏