有没有办法创建一个不改变程序中参数的函数

Is there a way to create a function that doesn't change the arrgument in the program

本文关键字:程序 改变 参数 函数 一个 创建 有没有      更新时间:2023-10-16

我创建了一个代码。我想在 2 个函数中使用相同的变量,但我不希望函数将值更改为另一个函数。为了让我自己更清楚,这里有一个例子:

int num1(int arr[5][6],int count);
int num2(int arr[5][6],int count2);
int main()
{
int count = 0;
int count2 = 0;
int arr[5][6] = {
{0, 0, 0, 1, 0, 0} ,   
{0, 0, 0, 0, 0, 0} ,   
{0, 0, 0, 0, 0, 0} ,
{0, 0, 0, 0, 0, 0} ,
{0, 0, 0, 0, 0, 0}
};
cout << num1(arr,count);
cout << num2(arr,count2);
return 0;
}
int num1(int arr[5][6],int count){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
if(arr[i][j] == 1){
count++;
arr[i][j] = 0;
}
}
}
return count;
}
int num2(int arr[5][6],int count2){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
if(arr[i][j] == 1){
count2++;
arr[i][j] = 0;
}
}
}
return count2;
}

此代码将打印 1 和 0,因为 num1 将 arr 中唯一的"1"更改为"0",并且由于 num2 将获得一个所有位置都有 0 的数组。 我想要的是让两个函数都打印 1,这样输出将是"11"而不是10。不,在不制作新数组的情况下,我真的很想知道是否有办法用单个数组做到这一点

C数组不像 C++(或 C(中的大多数其他东西那样支持正确的值语义。 正如人们所期望的那样工作的替代方案是std::array. 要获得 6 宽 x 5 高的阵列,类型为std::array<std::array<int, 6>, 5>。 由于这有点冗长,您可能需要一个using语句,例如

using arr_6_5 = std::array<std::array<int, 6>, 5>;

编辑:不幸的是,声明这样的数组有点烦人。 每个数组实际上需要两层大括号:一层用于包装std::array,另一层用于包装的 C 样式数组(但是,这些间接层在编译过程中被消除(。

const arr_6_5 arr = {{
{{0, 0, 0, 1, 0, 0}} ,   
{{0, 0, 0, 0, 0, 0}} ,   
{{0, 0, 0, 0, 0, 0}} ,
{{0, 0, 0, 0, 0, 0}} ,
{{0, 0, 0, 0, 0, 0}}
}};

您可以将num1num2的类型签名更改为

int num1(arr_6_5 arr, int count);
int num2(arr_6_5 arr, int count);

如果您确实要编辑原始数组,则它是arr_6_5 & arr,如果您想读取原始数组而不复制,则arr_6_5 const& arr

由于您实际上是将指向 2D 数组的指针传递给函数,因此如果不修改 main 函数中的数组arr,就无法修改参数arr

一种可能的解决方案是将arr作为const传递,然后将其复制到临时数组中进行修改。

int num1(const int arr[5][6],int count){
int arrLoc[5][6];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
arrLoc[i][j] = arr[i][j];
if (arrLoc[i][j] == 1) {
count++;
arrLoc[i][j] = 0;
}
}
}
// mutate local copy while leaving `arr` unmodified
mutation(arrLoc);
return count;
}