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

时间:2019-08-07 19:41:33

标签: c++

我创建了一个代码,我想在2个函数中使用相同的变量,但是我不想让功能将值更改为其他函数。为了使自己更清楚,下面是一个示例:

org.fmod.FMOD.init(Context var0)

此代码将打印1 and 0,因为num1将arr中唯一的'1'更改为'0',并且因为num2将获得一个数组,所有位置均为0。我想要的是打印1的函数,因此将在onCreate(Bundle bundle)中插入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; } 的输出。而且,不做一个新数组,我真的很想知道是否有一种方法可以处理单个数组

2 个答案:

答案 0 :(得分:6)

C数组不像C ++(或C)中的大多数其他事物那样支持正确的值语义。确实可以预期的一种替代方法是std::array。要使您的6乘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。 / p>

答案 1 :(得分:2)

由于本质上是将指向2D数组的指针传递给函数,因此无法在不修改主函数中的数组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;
}