C++中如何使函数返回多个数组

python转c++最大难点个人感觉就是返回数组,下面对各种方法进行记录:

1. 将待返回的数组在外部进行创建,之后作为函数的输入参数被修改,由于函数不需要返回值,不会产生内存泄露之类的问题。举例如下:

#include <iostream>
const int ArSize = 12;
void sum_and_sub(int arr1[], int arr2[], int ArSize, int sum_result[], int sub_result[]);
int main()
{
	using namespace std;
	int arr1[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	int arr2[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	int sum_result[ArSize], sub_result[ArSize];
	sum_and_sub(arr1, arr2, ArSize, sum_result, sub_result);
	for (int i = 0; i < ArSize; i++)
	{
		cout << sum_result[i] << " ";
	};
	cout << endl;
	for (int i = 0; i < ArSize; i++)
	{
		cout << sub_result[i] << " ";
	};
	cout << endl;
	return 0;
}
void sum_and_sub(int arr1[], int arr2[], int ArSize, int sum_result[], int sub_result[])
{
	for (int i = 0; i < ArSize; i++)
	{
		sum_result[i] = arr1[i] + arr2[i];
		sub_result[i] = arr1[i] - arr2[i];
	};
}

这种写法的问题很明显:

首先是写法复杂,因为要预先声明多个输入多个输出;

其次是因为你需要的输入和输出都是作为函数的输入,所以容易混淆;

最后在某些情况下会导致未初始化的值。

2. 结构化,上述函数的前两个问题都可以通过结构化来避免。举例如下:

#include <iostream>
const int ArSize = 12;

struct Result {
	int sum_result[ArSize];
	int sub_result[ArSize];
	Result()
	{
		memset(this, 0, sizeof(Result));
	}
};

Result sum_and_sub(int arr1[], int arr2[], int ArSize);

using namespace std;

int main()
{
	int arr1[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	int arr2[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	Result results = sum_and_sub(arr1, arr2, ArSize);
	for (int i = 0; i < ArSize; i++)
	{
		cout << results.sum_result[i] << " ";
	};
	cout << endl;
	for (int i = 0; i < ArSize; i++)
	{
		cout << results.sub_result[i] << " ";
	};
	cout << endl;
	return 0;
}

Result sum_and_sub(int arr1[], int arr2[], int ArSize)
{
	Result results;
	for (int i = 0; i < ArSize; i++)
	{
		//cout << results.sum_result[i];
		results.sum_result[i] = arr1[i] + arr2[i];
		results.sub_result[i] = arr1[i] - arr2[i];
	};
	return results;
}

这种写法相对来说比上面显得整洁,结构化也比较好管理。

后续还有用指针的写法,后续再写。

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值