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;
}
这种写法相对来说比上面显得整洁,结构化也比较好管理。
后续还有用指针的写法,后续再写。