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

R4Z*_*4Z7 1 c++

我创建了一个代码,我想在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;
}
Run Code Online (Sandbox Code Playgroud)

这段代码将打印1和0,因为num1将arr中唯一的“ 1”更改为“ 0”,并且由于该num2将获得一个数组,该数组的所有位置都为0。我想要的是打印两个函数所以输出将被"11"insted的的10。而且,不做一个新数组,我真的很想知道是否有一种方法可以处理单个数组

heg*_*000 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>;
Run Code Online (Sandbox Code Playgroud)

编辑:不幸的是,声明这样的数组有点烦人。实际上,每个数组需要两层花括号:一层用于包装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}}
}};
Run Code Online (Sandbox Code Playgroud)

然后您将num1和的类型签名更改num2

int num1(arr_6_5 arr, int count);
int num2(arr_6_5 arr, int count);
Run Code Online (Sandbox Code Playgroud)

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