dimanche 24 mai 2020

Pass Array to Recursive Function While Modifying It C++

I have a recursive function that takes a 2D array as a parameter in C++. The contents of this 2D array are to be unique among all recursive calls of this function.

I would like to modify this array each time before I make the recursive call. How can I do this without modifying the array for both of the 2 recursive calls, just for the current call?

Here is what I am trying to accomplish:

void foo(int a[10][10]) {
  // imagine base case above
  // modify array, i.e. set a[2][2] to '5'
  foo(a);
  // modify array i.e. set a[2][2] to '3'
  foo(a);
}

I tried the following, which resulted in a compiler error:

void foo(int a[10][10]) {
  // imagine base case above
  foo(a[2][2] = 5);
  foo(a[2][2] = 3);
}

The idea is that I want the array to be independent among recursive calls, for example, I don't want the set a[2][2] = 5 to apply to the next recursive call. I want that array modification to be "reverted", in a sense, before I apply the next modification (change).

This is easy to accomplish if I were just passing an int as an argument. For example, I could do:

void foo(int a) {
  // imagine base case above
  // increase a by 1
  foo(a + 1);
  // decrease a by 4
  foo(a - 4);
}

You can see here how easy it is to make the modifications without affecting the following recursive call.

My question here is how I can make changes along the same lines with an array.

Aucun commentaire:

Enregistrer un commentaire